TableAjax.php.TableAjax.js 150 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957
  1. if (!URI_BASE) throw "Missing URI_BASE"; // => Request::getPathUri()
  2. if (!URI_WPS) throw "Missing URI_WPS";
  3. if (!global.jQuery) throw "Missing jQuery"
  4. var $ = global.jQuery
  5. var DBG = DBG || false;
  6. var DBG1 = true;
  7. var createReactClass = global.p5VendorJs.createReactClass;
  8. var h = global.p5VendorJs.React.createElement;
  9. var ReactDOM = global.p5VendorJs.ReactDOM;
  10. var Redux = global.p5VendorJs.Redux;
  11. var ReduxThunk = global.p5VendorJs.ReduxThunk;
  12. var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
  13. var p5UI__FieldCheckboxSearch = global.p5VendorJs['p5UI__FieldCheckboxSearch'];
  14. var p5UI__FieldCheckboxLoading = global.p5VendorJs['p5UI__FieldCheckboxLoading'];
  15. if (!String.prototype.startsWith) { // TODO: to global js utils
  16. String.prototype.startsWith = function(search, pos) {
  17. return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
  18. };
  19. }
  20. p5WfsRefFilter = (function () { // convert GET param key ogc filter for ref
  21. return {
  22. parse: function (filterKey) {
  23. if (filterKey.startsWith('Ref_From_')) return { type: 'From', idInstance: filterKey.substr('Ref_From_'.length) };
  24. if (filterKey.startsWith('Ref_To_')) return { type: 'To', idInstance: filterKey.substr('Ref_To_'.length) };
  25. return null;
  26. }
  27. };
  28. })();
  29. var p5WPSUtils__createConvertToWpsDataInputFunction = function (identifier) {
  30. return function (value) {
  31. if (!value) return null; // WPS function require value, but for eg. featureQuery mey be empty
  32. return { // "wps:Input"
  33. identifier: identifier, // "ows:Identifier"
  34. // title: "...", // "ows:Title"
  35. data: { literalData: { value: value } }, // "wps:Data"
  36. // reference: "???", // "wps:Reference"
  37. // boundingBoxData: "???", // "wps:BoundingBoxData"
  38. };
  39. }
  40. };
  41. var p5WPSHelper_generateProcessSelectFeatureWithArgs = function (identifier, args) {
  42. var dataInputs = Object.keys(args).reduce(function (ret, argName) {
  43. var value = args[argName];
  44. var convertValueToWpsDataInput = p5WPSUtils__createConvertToWpsDataInputFunction(argName);
  45. return (p5Utils__isArray(value))
  46. ? ret.concat( value.map( convertValueToWpsDataInput ) )
  47. : ret.concat([ convertValueToWpsDataInput(value) ])
  48. ;
  49. }, []).filter(function (wpsTag) {
  50. return !! wpsTag;
  51. })
  52. return {
  53. identifier: identifier, // "ows:Identifier"
  54. dataInputs: dataInputs,
  55. responseForm: { // "wps:ResponseForm"
  56. // rawDataOutput: "???", // "wps:RawDataOutput"
  57. // responseDocument: "???", // "wps:ResponseDocument"
  58. }
  59. }
  60. }
  61. var p5WPS_executeFeatureProcess = function(identifier) {
  62. return function (wpsArgs) { // TODO: ns, listPrimaryKeys
  63. return new Promise(function (resolve, reject) {
  64. var process = p5WPSHelper_generateProcessSelectFeatureWithArgs(identifier, wpsArgs);
  65. OpenLayers.Request.POST({
  66. url: URI_WPS,
  67. data: new OpenLayers.Format.WPSExecute().write(process),
  68. callback: function (response) {
  69. try {
  70. var txt = response.responseText || ''
  71. if (!txt) throw "Empty response";
  72. var responseJson = JSON.parse(txt)
  73. if ('success' != responseJson.type) throw "Error response type '" + responseJson.type + "'";
  74. if (!responseJson.body || !responseJson.body.selected) throw "Brak danych";
  75. var listSelectedPks = Object.keys(responseJson.body.selected).filter(function (pk) {
  76. return responseJson.body.selected[pk];
  77. })
  78. var totalSelected = responseJson.body.totalSelected;
  79. DBG && console.log('wps('+identifier+') response', {response, responseJson, selected: responseJson.body.selected, resolve: listSelectedPks});
  80. resolve({
  81. selected: listSelectedPks,
  82. totalSelected: totalSelected,
  83. })
  84. } catch (e) {
  85. reject('' + e)
  86. return;
  87. }
  88. },
  89. // success: function (response) {
  90. // },
  91. // failure: function (response) {
  92. // }
  93. });
  94. });
  95. }
  96. };
  97. var p5WPS__selecFeature = p5WPS_executeFeatureProcess('p5:selectFeature');
  98. var p5WPS__unselectFeature = p5WPS_executeFeatureProcess('p5:unselectFeature');
  99. var p5WPS__unselecAllFeatures = p5WPS_executeFeatureProcess('p5:unselectAllFeatures');
  100. var p5WPS__getSelectedFeatures = p5WPS_executeFeatureProcess('p5:getSelectedFeatures');
  101. var p5WPS__selectAllFeaturesMatchingFilter = p5WPS_executeFeatureProcess('p5:selectAllFeaturesMatchingFilter');
  102. function p5Utils__arrayRemove(array, toRemoveItem) {
  103. return array.filter(function (item) {
  104. return ( item !== toRemoveItem );
  105. });
  106. }
  107. function p5Utils__mapToQuery(map, callback) {
  108. var mapCallback = ('function' === typeof callback) ? callback : function (key) {
  109. return '' + key + '=' + encodeURIComponent(map.get(key));
  110. };
  111. return Array.from(map.keys()).sort()
  112. .map(mapCallback)
  113. .join('&')
  114. }
  115. function p5Utils__mapToQueryWithKeyPrefix(map, keyPrefix, callback) {
  116. var mapCallback = ('function' === typeof callback) ? callback : function (key) {
  117. return '' + (keyPrefix || '') + key + '=' + encodeURIComponent(map.get(key));
  118. };
  119. return p5Utils__mapToQuery(map, mapCallback)
  120. }
  121. function p5Utils__objectToQueryWithKeyPrefix(obj, prefix, callback) {
  122. if (!obj) return '';
  123. var mapCallback = ('function' === typeof callback) ? callback : function (key) {
  124. return '' + key + '=' + encodeURIComponent(obj[key]);
  125. };
  126. return Object.keys(obj).sort()
  127. .map(mapCallback)
  128. .join('&')
  129. }
  130. function fixSelectAllInSelectedState(state) {
  131. var len = state.listPrimaryKeys.length;
  132. var selLen = state.selected.length;
  133. var isAllSelected = ( len > 0 && selLen >= len ); // selected array may contain 'select-all'
  134. for (var i = 0, pk = ''; i < len; i++) {
  135. pk = state.listPrimaryKeys[i];
  136. if (-1 === state.selected.indexOf(pk)) {
  137. isAllSelected = false;
  138. break;
  139. }
  140. }
  141. // DBG && console.log('fixSelectAllInSelectedState', { isAllSelected, state });
  142. var isSelectedSelectAll = ( -1 !== state.selected.indexOf('select-all') );
  143. if (isAllSelected && !isSelectedSelectAll) return Object.assign(state, {
  144. selected: ['select-all'].concat(state.selected)
  145. });
  146. if (!isAllSelected && isSelectedSelectAll) return Object.assign(state, {
  147. selected: p5Utils__arrayRemove(state.selected, 'select-all'),
  148. });
  149. return state;
  150. }
  151. function selectedStore(state, action) {
  152. var prevState = state || { isLoading: false, selected: [], loading: [], listPrimaryKeys: [], totalSelected: 0 };
  153. DBG && console.log('DBG::selectedStore', { prevState, action });
  154. switch (action.type) {
  155. case 'SET_CHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  156. loading: p5Utils__arrayRemove(prevState.loading, action.primaryKey),
  157. selected: prevState.selected.concat(action.primaryKey),
  158. totalSelected: action.totalSelected,
  159. }));
  160. case 'SET_UNCHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  161. loading: p5Utils__arrayRemove(prevState.loading, action.primaryKey),
  162. selected: p5Utils__arrayRemove(prevState.selected, action.primaryKey),
  163. totalSelected: action.totalSelected,
  164. }));
  165. case 'SET_LIST_CHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  166. loading: [], // TODO: p5Utils__arrayExcept(prevState.loading, action.listPrimaryKeys),
  167. selected: [].concat(action.listPrimaryKeys), // TODO: p5Utils__arrayUniqueUnion(prevState.selected, action.listPrimaryKeys)
  168. totalSelected: action.totalSelected,
  169. }));
  170. case 'SET_LIST_UNCHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  171. loading: [], // TODO: p5Utils__arrayExcept(prevState.loading, action.listPrimaryKeys),
  172. selected: [], // TODO: p5Utils__arrayUniqueUnion(prevState.selected, action.listPrimaryKeys)
  173. totalSelected: action.totalSelected,
  174. }));
  175. case 'SET_LOADING': return Object.assign(prevState, {
  176. loading: prevState.loading.concat(action.primaryKey)
  177. });
  178. case 'SET_LIST_LOADING': return Object.assign(prevState, {
  179. loading: [].concat(action.listPrimaryKeys)
  180. });
  181. case 'SET_PRIMARY_KEYS': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
  182. listPrimaryKeys: [].concat(action.listPrimaryKeys),
  183. loading: [].concat(action.listPrimaryKeys)
  184. }));
  185. // case 'SET_ERROR_MSG': return Object.assign(prevState, {
  186. // errorMsg: action.errorMsg
  187. // });
  188. default: return prevState;
  189. }
  190. }
  191. function selectedActions(idContext) {
  192. var idContext = idContext || null;
  193. function setChecked(primaryKey, totalSelected) {
  194. return { type: 'SET_CHECKED', primaryKey: primaryKey, totalSelected: totalSelected }
  195. }
  196. function setUnchecked(primaryKey, totalSelected) {
  197. return { type: 'SET_UNCHECKED', primaryKey: primaryKey, totalSelected: totalSelected }
  198. }
  199. function setLoading(primaryKey) {
  200. return { type: 'SET_LOADING', primaryKey: primaryKey }
  201. }
  202. function setListChecked(listPrimaryKeys, totalSelected) {
  203. return { type: 'SET_LIST_CHECKED', listPrimaryKeys: listPrimaryKeys, totalSelected: totalSelected }
  204. }
  205. function setListUnchecked(listPrimaryKeys, totalSelected) {
  206. return { type: 'SET_LIST_UNCHECKED', listPrimaryKeys: listPrimaryKeys, totalSelected: totalSelected }
  207. }
  208. function setListLoading(listPrimaryKeys) {
  209. return { type: 'SET_LIST_LOADING', listPrimaryKeys: listPrimaryKeys }
  210. }
  211. function setErrorMsg(errorMsg) {
  212. return { type: 'SET_ERROR_MSG', errorMsg: errorMsg }
  213. }
  214. function toggle(namespace, primaryKey, checked) {
  215. if ('select-all' === primaryKey) return toggleAll(namespace, checked);
  216. return function(dispatch, getState) {
  217. // var state = getState();
  218. dispatch(setLoading(primaryKey));
  219. var reqArgs = { typeName: namespace, primaryKey: [ primaryKey ] };
  220. if (idContext) reqArgs.idContext = idContext;
  221. var reqPromise = checked ? p5WPS__selecFeature(reqArgs) : p5WPS__unselectFeature(reqArgs);
  222. return reqPromise.then(function (response) {
  223. DBG && console.log('DBG::async toggle action: (pk:'+primaryKey+') dispatch...');
  224. dispatch( checked ? setChecked(primaryKey, response.totalSelected) : setUnchecked(primaryKey, response.totalSelected) );
  225. }).catch(function (e) {
  226. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA1: ' + e});
  227. DBG && console.warn('DBG::async toggle action: (pk:'+primaryKey+') ERROR', e);
  228. // dispatch( checked ? setUnchecked(primaryKey) : setChecked(primaryKey) );
  229. // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  230. dispatch( setListLoading([]) );
  231. });
  232. }
  233. }
  234. function setPrimaryKeys(namespace, listPrimaryKeys) { // TODO: should set list primaryKeys, change checkboxes to loading and fetch its state, then update gui
  235. DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
  236. return function(dispatch, getState) {
  237. dispatch({ type: 'SET_PRIMARY_KEYS', listPrimaryKeys: listPrimaryKeys });
  238. // dispatch( setListLoading(listPrimaryKeys) );
  239. if (!listPrimaryKeys.length) return;
  240. var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys };
  241. if (idContext) reqArgs.idContext = idContext;
  242. return p5WPS__getSelectedFeatures(reqArgs).then(function (listSelected) {
  243. DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
  244. dispatch( setListChecked(listSelected.selected, listSelected.totalSelected) );
  245. }).catch(function (e) {
  246. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA2: ' + e});
  247. DBG && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
  248. // var fullListPks = ['select-all'].concat(listPrimaryKeys);
  249. // dispatch( setListUnchecked(fullListPks) );
  250. // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  251. dispatch( setListLoading([]) );
  252. });
  253. }
  254. }
  255. function toggleAll(namespace, checked) {
  256. var primaryKey = 'select-all';
  257. return function(dispatch, getState) {
  258. // var state = getState();
  259. dispatch(setLoading(primaryKey));
  260. var state = getState();
  261. var listPrimaryKeys = state.listPrimaryKeys;
  262. var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys };
  263. if (idContext) reqArgs.idContext = idContext;
  264. var reqPromise = checked ? p5WPS__selecFeature(reqArgs) : p5WPS__unselectFeature(reqArgs);
  265. return reqPromise.then(function (response) {
  266. DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
  267. dispatch( checked ? setListChecked(response.selected, response.totalSelected) : setListUnchecked(response.selected, response.totalSelected) );
  268. }).catch(function (e) {
  269. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA3: ' + e});
  270. DBG && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
  271. // var fullListPks = ['select-all'].concat(listPrimaryKeys)
  272. // dispatch( checked ? setListUnchecked(fullListPks) : setListChecked(fullListPks) );
  273. // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  274. dispatch( setListLoading([]) );
  275. });
  276. }
  277. }
  278. function unselectAll(namespace) {
  279. // dispatch(setLoading());
  280. return function(dispatch, getState) {
  281. var reqArgs = { typeName: namespace };
  282. if (idContext) reqArgs.idContext = idContext;
  283. var reqPromise = p5WPS__unselecAllFeatures(reqArgs);
  284. return reqPromise.then(function (response) {
  285. DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
  286. // dispatch( setListChecked(response.selected, response.totalSelected) );
  287. dispatch( setListChecked([], 0) );
  288. }).catch(function (e) {
  289. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA4: ' + e});
  290. DBG && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
  291. // var fullListPks = ['select-all'].concat(listPrimaryKeys)
  292. // dispatch( checked ? setListUnchecked(fullListPks) : setListChecked(fullListPks) );
  293. // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  294. // dispatch( setListLoading([]) );
  295. });
  296. };
  297. }
  298. function selectAllMatchingFilter(namespace, filterQuery) {
  299. DBG && console.log('DBG::selectAllMatchingFilter', { filterQuery });
  300. return function(dispatch, getState) {
  301. DBG && console.log('DBG::selectAllMatchingFilter state', state);
  302. var state = getState();
  303. var listPrimaryKeys = state.listPrimaryKeys;
  304. var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys, filterQuery: filterQuery };
  305. if (idContext) reqArgs.idContext = idContext;
  306. return p5WPS__selectAllFeaturesMatchingFilter(reqArgs).then(function (listSelected) {
  307. DBG && console.log('DBG::selectAllMatchingFilter dispatch success');
  308. dispatch( setListChecked(listSelected.selected, listSelected.totalSelected) );
  309. }).catch(function (e) {
  310. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA5: ' + e});
  311. DBG && console.warn('DBG::selectAllMatchingFilter ERROR dispatch error');
  312. // var fullListPks = ['select-all'].concat(listPrimaryKeys);
  313. // dispatch( setListUnchecked(fullListPks) );
  314. // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
  315. dispatch( setListLoading([]) );
  316. });
  317. }
  318. }
  319. return {
  320. setPrimaryKeys: setPrimaryKeys,
  321. setChecked: setChecked,
  322. setUnchecked: setUnchecked,
  323. toggle: toggle,
  324. unselectAll: unselectAll,
  325. selectAllMatchingFilter: selectAllMatchingFilter,
  326. }
  327. }
  328. function createFilterStoreWithInitialData(initialFilter) {
  329. var initialState = { isLoading: false, isEmpty: true, filter: new Map(), specialFilter: new Map(), currSortCol: '', currSortFlip: false }
  330. Object.keys(initialFilter).forEach(function (key) {
  331. if ('currSortCol' === key) {
  332. initialState.currSortCol = initialFilter[key]
  333. } else if ('currSortFlip' === key) {
  334. initialState.currSortFlip = initialFilter[key]
  335. } else if ('f_' === key.substr(0, 2)) {
  336. initialState.filter.set(key.substr(2), initialFilter[key])
  337. } else if ('sf_' === key.substr(0, 3)) {
  338. initialState.specialFilter.set(key.substr(3), initialFilter[key])
  339. }
  340. })
  341. return function filterStore(state, action) {
  342. var prevState = state || initialState;
  343. DBG && console.warn('DBG:filterStore:' + action.type, action);
  344. switch (action.type) {
  345. // case 'SET_FILTER': return fixFilterState(Object.assign({}, prevState, {
  346. // filter: Object.assign(prevState.filter, {
  347. // [action.fieldName]: action.value
  348. // })
  349. // }));
  350. case 'TOGGLE_SORT': {
  351. return Object.assign(prevState, {
  352. currSortCol: action.fieldName,
  353. currSortFlip: !prevState.currSortFlip
  354. })
  355. }
  356. case 'SET_FILTER': {
  357. if (action.value) {
  358. prevState.filter.set(action.fieldName, action.value);
  359. } else {
  360. prevState.filter.delete(action.fieldName);
  361. }
  362. return Object.assign(prevState, {
  363. isEmpty: (0 === prevState.specialFilter.size && 0 === prevState.filter.size)
  364. })
  365. }
  366. case 'SET_SPECIAL_FILTER': {
  367. if (action.value) {
  368. prevState.specialFilter.set(action.fieldName, action.value);
  369. } else {
  370. prevState.specialFilter.delete(action.fieldName);
  371. }
  372. return Object.assign(prevState, {
  373. isEmpty: (0 === prevState.specialFilter.size && 0 === prevState.filter.size)
  374. })
  375. }
  376. case 'CLEAR_ALL_FILTERS': {
  377. prevState.filter.clear();
  378. prevState.specialFilter.clear();
  379. return Object.assign(prevState, {
  380. isLoading: false, isEmpty: true
  381. });
  382. }
  383. case 'SET_LOADING': return Object.assign(prevState, { // TODO: is loading for filter store or another store for rows?
  384. isLoading: true
  385. });
  386. case 'UNSET_LOADING': return Object.assign(prevState, {
  387. isLoading: false
  388. });
  389. default: return prevState;
  390. }
  391. }
  392. }
  393. function filterActions() {
  394. var delay = 450;
  395. var _filterTimeout = {};
  396. var _clearTimer = function (fieldName) {
  397. if (_filterTimeout[fieldName]) {
  398. clearTimeout(_filterTimeout[fieldName]);
  399. }
  400. }
  401. var _clearAllTimers = function () {
  402. Object.keys(_filterTimeout).forEach(_clearTimer);
  403. }
  404. function clearAllFilters() {
  405. DBG && console.log('DBG:filterStore:clearAllFilters');
  406. _clearAllTimers();
  407. return { type: 'CLEAR_ALL_FILTERS' };
  408. }
  409. function toggleSort(fieldName) {
  410. DBG && console.log('DBG:filterStore:toggleSort', { fieldName });
  411. return { type: 'TOGGLE_SORT', fieldName: fieldName };
  412. }
  413. function setFilter(fieldName, value) {
  414. DBG && console.log('DBG:filterStore:setFilter', { fieldName, value });
  415. return { type: 'SET_FILTER', fieldName: fieldName, value: value };
  416. }
  417. function setSpecialFilter(fieldName, value) {
  418. DBG && console.log('DBG:filterStore:setSpecialFilter', { fieldName, value });
  419. return { type: 'SET_SPECIAL_FILTER', fieldName: fieldName, value: value };
  420. }
  421. function delayFilter(fieldName, value) {
  422. DBG && console.log('DBG:filterStore:delayFilter', { fieldName, value });
  423. return function(dispatch, getState) {
  424. // var state = getState();
  425. // dispatch(setLoading(primaryKey));
  426. return new Promise(function (resolve, reject) {
  427. DBG && console.log('DBG:filterStore:delayFilter::#1', { fieldName, value });
  428. _clearTimer(fieldName);
  429. _filterTimeout[fieldName] = setTimeout(function () {
  430. // reject("Error");
  431. resolve(value);
  432. }, delay);
  433. }).then(function (value) {
  434. DBG && console.log('DBG:filterStore:delayFilter::#3 resolve ', { fieldName, value });
  435. dispatch( { type: 'SET_FILTER', fieldName: fieldName, value: value } );
  436. }).catch(function (e) {
  437. p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA6: ' + e});
  438. })
  439. }
  440. }
  441. return {
  442. setFilter: setFilter,
  443. setSpecialFilter: setSpecialFilter,
  444. delayFilter: delayFilter,
  445. clearAllFilters: clearAllFilters,
  446. toggleSort: toggleSort,
  447. }
  448. }
  449. global['P5UI__TableAjaxRowCheckbox'] = createReactClass({
  450. // props.namespace: PropTypes.string.isRequired
  451. // props.primaryKey: PropTypes.string.isRequired
  452. // props.store: Redux store with state: { isLoading bool, selected array of strings }
  453. // props.actions: Redux store actions
  454. getStateFromStore: function () {
  455. var state = this.props.store.getState();
  456. return {
  457. disabled: this.props.disabled ? true : false,
  458. isLoading: (-1 !== state.loading.indexOf(this.props.primaryKey)),
  459. checked: (-1 !== state.selected.indexOf(this.props.primaryKey))
  460. };
  461. },
  462. getInitialState: function () {
  463. return this.getStateFromStore();
  464. },
  465. componentDidMount: function () {
  466. DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::componentDidMount (pk:'+this.props.primaryKey+')');
  467. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  468. },
  469. componentWillUnmount: function () {
  470. this.unsubscribe()
  471. },
  472. storeUpdated: function () {
  473. DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::storeUpdated (pk:'+this.props.primaryKey+')');
  474. this.setState(this.getStateFromStore())
  475. },
  476. shouldComponentUpdate: function (nextProps, nextState) {
  477. DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::shouldComponentUpdate (pk:'+this.props.primaryKey+')', { state: this.state, nextState});
  478. return (
  479. this.state.isLoading !== nextState.isLoading
  480. || this.state.checked !== nextState.checked
  481. );
  482. },
  483. handleChange: function (checked) { // handleChange: function (event) {
  484. DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::handleChange (pk:'+this.props.primaryKey+')', { checked: checked });
  485. this.props.store.dispatch( this.props.actions.toggle( this.props.namespace, this.props.primaryKey, checked ) )
  486. },
  487. render: function () {
  488. DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::render (pk:'+this.props.primaryKey+')', { props: this.props, state: this.state });
  489. return h(p5UI__FieldCheckboxLoading, {
  490. size: 20,
  491. color: '#999',
  492. checked: this.state.checked,
  493. disabled: this.state.disabled,
  494. isLoading: this.state.isLoading,
  495. onChange: this.handleChange
  496. });
  497. }
  498. });
  499. global['P5UI__TableAjaxSelectedInfo'] = createReactClass({
  500. // props.namespace: PropTypes.string.isRequired
  501. // props.store: Redux store with state: { isLoading bool, selected array of strings }
  502. // props.actions: Redux store actions
  503. getStateFromStore: function () {
  504. var state = this.props.store.getState();
  505. var wasAllSelected = (this.state) && this.state.isUpdatedAllSelected;
  506. var isAllSelected = ( -1 !== state.selected.indexOf('select-all') );
  507. DBG && console.log('DBG: getStateFromStore (ns:'+this.props.namespace+')', { isAllSelected, state });
  508. return {
  509. // isLoading: state.isLoading || 0, // add ?
  510. isUpdatedAllSelected: ( !wasAllSelected && isAllSelected ),
  511. totalSelected: state.totalSelected || 0,
  512. };
  513. },
  514. getInitialState: function () {
  515. return this.getStateFromStore();
  516. },
  517. componentDidMount: function () {
  518. DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::componentDidMount (ns:'+this.props.namespace+')');
  519. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  520. },
  521. componentWillUnmount: function () {
  522. this.unsubscribe()
  523. },
  524. storeUpdated: function () {
  525. DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::storeUpdated (ns:'+this.props.namespace+')');
  526. this.setState(this.getStateFromStore())
  527. },
  528. shouldComponentUpdate: function (nextProps, nextState) {
  529. DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::shouldComponentUpdate (ns:'+this.props.namespace+')', { state: this.state, nextState});
  530. return (
  531. this.state.totalSelected !== nextState.totalSelected
  532. || this.state.isUpdatedAllSelected !== nextState.isUpdatedAllSelected
  533. );
  534. },
  535. handleUnselectAll: function (event) {
  536. DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::handleUnselectAll (ns:'+this.props.namespace+')');
  537. this.props.store.dispatch( this.props.actions.unselectAll( this.props.namespace ) )
  538. },
  539. handleSelectAllByFilter: function (event) {
  540. DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::handleSelectAllByFilter (ns:'+this.props.namespace+')');
  541. // this.props.store.dispatch( this.props.actions.unselectAll( this.props.namespace ) )
  542. this.props.onSelectAllMatching()
  543. },
  544. render: function () {
  545. DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::render (ns:'+this.props.namespace+')', { props: this.props, state: this.state });
  546. return h('div', { style: {
  547. padding: '0 4px'
  548. } }, [
  549. h('span', {}, "Wybrano " + this.state.totalSelected),
  550. (this.state.totalSelected > 0) ? h('i', {
  551. onClick: this.handleUnselectAll,
  552. className: "glyphicon glyphicon-remove",
  553. style: {
  554. marginLeft: '4px',
  555. cursor: 'pointer',
  556. color: 'red',
  557. opacity: '0.5'
  558. },
  559. title: this.props.title || 'Usuń wszystkie zaznaczenia'
  560. }) : null,
  561. (this.state.isUpdatedAllSelected) && h('br'),
  562. (this.state.isUpdatedAllSelected) && h('a', {
  563. onClick: this.handleSelectAllByFilter,
  564. className: "btn btn-xs btn-link",
  565. style: {
  566. marginLeft: '4px',
  567. },
  568. title: this.props.title || 'Zaznacz wszystkie pasujące do wyszukiwania'
  569. }, "+ wszystkie"),
  570. ])
  571. }
  572. });
  573. global['P5UI__TableAjaxSpecialFilter'] = createReactClass({
  574. // props.store: Redux store with state: { isLoading bool, selected array of strings }
  575. // props.actions: Redux store actions
  576. // props.name: PropTypes.string.isRequired
  577. // props.values: PropTypes.array.isRequired
  578. // props.icon: PropTypes.string.isRequired
  579. // props.label: PropTypes.string
  580. getStateFromStore: function () {
  581. var state = this.props.store.getState();
  582. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::getStateFromStore (name:'+this.props.name+')', { store: state, name: this.props.name, selected: state.specialFilter.get(this.props.name) });
  583. return {
  584. selected: state.specialFilter.get(this.props.name),
  585. };
  586. },
  587. getInitialState: function () {
  588. return this.getStateFromStore();
  589. },
  590. componentDidMount: function () {
  591. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::componentDidMount (name:'+this.props.name+')');
  592. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  593. },
  594. componentWillUnmount: function () {
  595. this.unsubscribe()
  596. },
  597. storeUpdated: function () {
  598. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::storeUpdated (name:'+this.props.name+')');
  599. this.setState(this.getStateFromStore())
  600. },
  601. shouldComponentUpdate: function (nextProps, nextState) {
  602. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::shouldComponentUpdate (name:'+this.props.name+')', { state: this.state, nextState});
  603. return (
  604. this.state.selected !== nextState.selected
  605. );
  606. },
  607. handleRemoveFilter: function (event) {
  608. this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, '') );
  609. },
  610. handleSetFilter: function (value) {
  611. this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, value) );
  612. },
  613. renderButton: function (buttonKey) {
  614. var option = buttonKey;
  615. var props = this.props.values[option];
  616. var value = props.value || '';
  617. var state = this.props.store.getState();
  618. DBG && console.warn('DBG:renderButton state', { state, props, value });
  619. var active = (value === this.state.selected);
  620. return h('button', {
  621. className: "btn btn-xs btn-default" + ( active ? " active" : "" ),
  622. onClick: function (event) {
  623. DBG && console.warn('DBG:renderButton click', { value });
  624. this.handleSetFilter(value);
  625. }.bind(this),
  626. }, option);
  627. },
  628. render: function () {
  629. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::render (name:'+this.props.name+')', { state: this.state, props: this.props });
  630. var label = this.props.label || this.props.name;
  631. return h('div', { className: "btn-group", style: { margin: '0 4px 0 0' } },
  632. [
  633. h('button', {
  634. className: "btn btn-xs btn-default",
  635. title: label,
  636. }, [
  637. h('i', { className: this.props.icon })
  638. ])
  639. ].concat(
  640. Object.keys(this.props.values).map(this.renderButton)
  641. ).concat(
  642. [
  643. h('button', {
  644. className: "btn btn-xs btn-default",
  645. title: "Kasuj filtr",
  646. disabled: !this.state.selected,
  647. onClick: this.handleRemoveFilter,
  648. style: { color: !this.state.selected ? '#bbb' : '#f00' }
  649. }, [
  650. h('i', { className: "glyphicon glyphicon-remove" })
  651. ])
  652. ]
  653. )
  654. );
  655. }
  656. });
  657. global['P5UI__TableAjaxSpecialFilterRelations'] = createReactClass({
  658. // props.store: Redux store with state: { isLoading bool, selected array of strings }
  659. // props.actions: Redux store actions
  660. // props.name: PropTypes.string.isRequired
  661. // props.values: PropTypes.array.isRequired
  662. // props.icon: PropTypes.string.isRequired
  663. // props.label: PropTypes.string
  664. // props.availableBackRefs: PropTypes.array.isRequired // array of objects { id, namespace, label }
  665. // props.availableChildRefs: PropTypes.array.isRequired // array of objects { id, namespace, label }
  666. getStateFromStore: function () {
  667. var state = this.props.store.getState();
  668. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::getStateFromStore (name:'+this.props.name+')', { store: state, name: this.props.name, selected: state.specialFilter.get(this.props.name) });
  669. var selected = []; // Array of { idInstance, primaryKey }
  670. state.specialFilter.forEach(function (value, key) {
  671. var refInfo = p5WfsRefFilter.parse(key); // null | { type: 'From' | 'To', idInstance: int }
  672. if (refInfo) {
  673. selected.push(Object.assign(refInfo, { primaryKey: value, filterKey: key }))
  674. }
  675. })
  676. DBG && console.log('TODO: DBG::P5UI__TableAjaxSpecialFilterRelations::getStateFromStore (name:'+this.props.name+')', { store: state, name: this.props.name, selected });
  677. return {
  678. selected: selected,
  679. };
  680. },
  681. getInitialState: function () {
  682. return this.getStateFromStore();
  683. },
  684. componentDidMount: function () {
  685. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::componentDidMount (name:'+this.props.name+')');
  686. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  687. },
  688. componentWillUnmount: function () {
  689. this.unsubscribe()
  690. },
  691. storeUpdated: function () {
  692. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::storeUpdated (name:'+this.props.name+')');
  693. this.setState(this.getStateFromStore())
  694. },
  695. shouldComponentUpdate: function (nextProps, nextState) {
  696. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::shouldComponentUpdate (name:'+this.props.name+')', { state: this.state, nextState});
  697. return (
  698. this.state.selected !== nextState.selected
  699. );
  700. },
  701. handleRemoveFilter: function (event) {
  702. this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, '') );
  703. },
  704. handleSetFilter: function (value) {
  705. this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, value) );
  706. },
  707. handleCreate: function () {
  708. // TODO: save swal reference to variable to avoid open twice?
  709. var inputOptions = {};
  710. if (this.props.availableBackRefs) this.props.availableBackRefs.forEach(function (instanceInfo) {
  711. inputOptions[ 'From_' + instanceInfo.id ] = "z " + instanceInfo.label || instanceInfo.namespace;
  712. });
  713. if (this.props.availableChildRefs) this.props.availableChildRefs.forEach(function (instanceInfo) {
  714. inputOptions[ 'To_' + instanceInfo.id ] = "do " + instanceInfo.label || instanceInfo.namespace;
  715. });
  716. swal({
  717. title: "Wybierz rodzaj relacji",
  718. input: 'select',
  719. inputOptions: inputOptions,
  720. inputPlaceholder: "Wybierz",
  721. showCancelButton: true,
  722. cancelButtonText: "Anuluj",
  723. animation: false,
  724. inputValidator: function (value) {
  725. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::inputValidator', value);
  726. return new Promise(function (resolve) {
  727. if (!value) {
  728. resolve('Nie wybrano obiektu');
  729. } else {
  730. resolve();
  731. }
  732. });
  733. },
  734. }).then(this.handleInstanceCreate) // args: { value: ... }
  735. },
  736. handleInstanceCreate: function (result) {
  737. if (!result.value) return; // cancel when result = { dismiss: "cancel" }
  738. var idInstance = '';
  739. var type = '';
  740. var instanceLabel = '';
  741. if ('From_' === result.value.substr(0, 'From_'.length)) {
  742. type = 'From';
  743. idInstance = result.value.substr('From_'.length);
  744. if (this.props.availableBackRefs) this.props.availableBackRefs.forEach(function (instanceInfo) {
  745. if (idInstance == instanceInfo.id) instanceLabel = instanceInfo.label || instanceInfo.namespace;
  746. });
  747. }
  748. else if ('To_' === result.value.substr(0, 'To_'.length)) {
  749. type = 'To';
  750. idInstance = result.value.substr('To_'.length);
  751. if (this.props.availableChildRefs) this.props.availableChildRefs.forEach(function (instanceInfo) {
  752. if (idInstance == instanceInfo.id) instanceLabel = instanceInfo.label || instanceInfo.namespace;
  753. });
  754. }
  755. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::handleInstanceCreate (name:'+this.props.name+') selected instance('+idInstance+')', { result: result, state: this.state, props: this.props, availableBackRefs: this.props.availableBackRefs });
  756. swal({
  757. title: "Wybierz obiekt",
  758. html: (instanceLabel) ? "typu: " + instanceLabel : "",
  759. input: 'text',
  760. inputPlaceholder: "Wybierz obiekt",
  761. showCancelButton: true,
  762. cancelButtonText: "Anuluj",
  763. animation: false,
  764. inputValidator: function (value) {
  765. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::inputValidator', value);
  766. return new Promise(function (resolve) {
  767. if (!value) {
  768. resolve('Nie podano obiektu');
  769. } else {
  770. resolve();
  771. }
  772. });
  773. },
  774. preConfirm: function (value) {
  775. return {
  776. type: type,
  777. idInstance: idInstance,
  778. primaryKey: value,
  779. }
  780. }
  781. }).then(this.handleInstancePrimaryKeySelected) // args: { value: { idInstance, primaryKey } }
  782. },
  783. handleInstancePrimaryKeySelected: function (result) {
  784. if (!result.value) return; // cancel when result = { dismiss: "cancel" }
  785. var type = result.value.type;
  786. var idInstance = result.value.idInstance;
  787. var primaryKey = result.value.primaryKey;
  788. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::handleInstancePrimaryKeySelected (name:'+this.props.name+') selected featureID('+idInstance+'.'+primaryKey+')', { result: result, state: this.state, props: this.props, availableBackRefs: this.props.availableBackRefs });
  789. this.props.store.dispatch( this.props.actions.setSpecialFilter('Ref_' + type + '_' + idInstance, primaryKey) );
  790. },
  791. renderButton: function (buttonKey) {
  792. var option = buttonKey;
  793. var props = this.props.values[option];
  794. var value = props.value || '';
  795. var state = this.props.store.getState();
  796. DBG && console.warn('DBG:renderButton state', { state, props, value });
  797. var active = (value === this.state.selected);
  798. return h('button', {
  799. className: "btn btn-xs btn-default" + ( active ? " active" : "" ),
  800. onClick: function (event) {
  801. DBG && console.warn('DBG:renderButton click', { value });
  802. this.handleSetFilter(value);
  803. }.bind(this),
  804. }, option);
  805. },
  806. renderLabel: function () {
  807. var label = this.props.label || this.props.name;
  808. return h('button', {
  809. className: "btn btn-xs btn-default",
  810. title: label,
  811. style: {
  812. color: '#31708f',
  813. backgroundColor: '#d9edf7',
  814. }
  815. }, [
  816. h('i', { className: this.props.icon }),
  817. " Filtr relacji: ",
  818. ]);
  819. },
  820. renderListSelected: function () { // @return array of react nodes
  821. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::this.props.availableBackRefs (name:'+this.props.name+')', { state: this.state, props: this.props, availableBackRefs: this.props.availableBackRefs });
  822. return this.state.selected.map(this.renderSelected);
  823. },
  824. renderSelected: function (selected) { // @selected: { type: 'From' | 'To', filterKey, idInstance, primaryKey }, @return react node
  825. var filterKey = selected.filterKey;
  826. var type = selected.type; // From | To - backRef | childRef
  827. var idInstance = selected.idInstance;
  828. var primaryKey = selected.primaryKey;
  829. var namespace = idInstance;
  830. var label = "" + idInstance + "." + primaryKey + "";
  831. if ('From' === type) {
  832. var foundInstanceInfo = this.props.availableBackRefs.filter(function (instanceInfo) {
  833. return ( parseInt(idInstance) === parseInt(instanceInfo.id) );
  834. });
  835. if (foundInstanceInfo.length > 0) label = 'z ' + foundInstanceInfo[0].label + "." + primaryKey;
  836. if (foundInstanceInfo.length > 0) namespace = foundInstanceInfo[0].namespace;
  837. } else if ('To' === type) {
  838. var foundInstanceInfo = this.props.availableChildRefs.filter(function (instanceInfo) {
  839. return ( parseInt(idInstance) === parseInt(instanceInfo.id) );
  840. });
  841. if (foundInstanceInfo.length > 0) label = 'do ' + foundInstanceInfo[0].label + "." + primaryKey;
  842. if (foundInstanceInfo.length > 0) namespace = foundInstanceInfo[0].namespace;
  843. }
  844. return h(P5UI__TableAjaxSpecialFilterRelationFrom, {
  845. filterKey: filterKey,
  846. label: label,
  847. namespace: namespace,
  848. primaryKey: primaryKey,
  849. store: this.props.store,
  850. actions: this.props.actions,
  851. });
  852. },
  853. renderBackRef: function () { // @return react node - button with dropdown to select primaryKey from parent instance + remove button if selected
  854. return null;
  855. },
  856. renderCreateButton: function () {
  857. return h('button', {
  858. className: "btn btn-xs btn-default",
  859. title: "Dodaj nowy filtr relacji",
  860. onClick: this.handleCreate,
  861. }, [
  862. h('i', { className: 'glyphicon glyphicon-plus' })
  863. ]);
  864. },
  865. render: function () {
  866. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::render (name:'+this.props.name+')', { state: this.state, props: this.props });
  867. return h('div', { className: "btn-group", style: { margin: '0 4px 0 0' } },
  868. [
  869. this.renderLabel(),
  870. ].concat(
  871. this.renderListSelected()
  872. ).concat([
  873. this.renderCreateButton()
  874. ])
  875. // Object.keys(this.props.values).map(this.renderButton)
  876. // ).concat(
  877. // [
  878. // h('button', {
  879. // className: "btn btn-xs btn-default",
  880. // title: "Kasuj filtr",
  881. // disabled: !this.state.selected,
  882. // onClick: this.handleRemoveFilter,
  883. // style: { color: !this.state.selected ? '#bbb' : '#f00' }
  884. // }, [
  885. // h('i', { className: "glyphicon glyphicon-remove" })
  886. // ])
  887. // ]
  888. );
  889. }
  890. });
  891. global['P5UI__TableAjaxSpecialFilterRelationFrom'] = createReactClass({
  892. handleRemoveFilter: function (event) {
  893. this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.filterKey, '') );
  894. },
  895. render: function () {
  896. DBG1 && console.log('DBG::P5UI__TableAjaxSpecialFilterRelationFrom::render (filterKey:'+this.props.filterKey+')', { state: this.state, props: this.props });
  897. var refInfo = p5WfsRefFilter.parse(this.props.filterKey); // null | { type: 'From' | 'To', idInstance: int }
  898. return h('button', {
  899. className: "btn btn-xs btn-default active",
  900. title: "Powiązane" + ( 'From' === refInfo.type ? " z " : " do " ) + this.props.namespace + " " + this.props.primaryKey,
  901. // onClick: this.handleUpdate, // TODO: paste param
  902. }, [
  903. this.props.label,
  904. h('i', {
  905. className: 'glyphicon glyphicon-remove',
  906. style: {
  907. color: '#f00',
  908. opacity: 0.5,
  909. marginLeft: "3px",
  910. },
  911. onClick: this.handleRemoveFilter,
  912. })
  913. ]);
  914. }
  915. });
  916. global['P5UI__TableAjaxSpecialFilters'] = createReactClass({
  917. // props.store: Redux store with state: { isLoading bool, selected array of strings }
  918. // props.actions: Redux store actions
  919. // props.namespace: PropTypes.string.isRequired
  920. // props.specialFilters: PropTypes.object.isRequired
  921. // props.specialFilters:
  922. // [Msgs] => stdClass Object
  923. // [icon] => glyphicon glyphicon-envelope
  924. // [label] => Wiadomości
  925. // [btns] => Array:
  926. // [WIADOMOSCI] => stdClass Object
  927. // [value] => HAS_MSGS
  928. // [NOWE] => stdClass Object
  929. // [value] => NEW_MSGS
  930. // [BRAK_WIAD.] => stdClass Object
  931. // [value] => NO_MSGS
  932. // [Status] => stdClass Object
  933. // [icon] => glyphicon glyphicon-question-sign
  934. // [btns] => Array:
  935. // [OCZEKUJACY] => stdClass Object
  936. // [value] => WAITING
  937. // [AKTYWNI] => stdClass Object
  938. // [value] => AKTYWNI
  939. // handleClick: function (event) {
  940. // DBG && console.log('DBG::P5UI__TableAjaxSpecialFilters::handleChange (ns:'+this.props.namespace+')', { checked: checked });
  941. // this.props.store.dispatch( this.props.actions.unselectAll( this.props.namespace ) )
  942. // },
  943. renderSpecialFilter: function (key) {
  944. var props = this.props.specialFilters[key];
  945. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilters::renderSpecialFilter (ns:'+this.props.namespace+')', { key: key, props, state: this.state });
  946. if ('RELATIONS' === props.type) {
  947. DBG && console.warn('DBG::P5UI__TableAjaxSpecialFilters::renderSpecialFilter TODO render RELATIONS filter (ns:'+this.props.namespace+')', { props, state: this.state });
  948. return h(P5UI__TableAjaxSpecialFilterRelations, {
  949. store: this.props.store,
  950. actions: this.props.actions,
  951. name: key,
  952. icon: props.icon,
  953. label: props.label,
  954. availableBackRefs: props.availableBackRefs,
  955. availableChildRefs: props.availableChildRefs,
  956. });
  957. }
  958. return h(P5UI__TableAjaxSpecialFilter, {
  959. store: this.props.store,
  960. actions: this.props.actions,
  961. name: key,
  962. icon: props.icon,
  963. label: props.label,
  964. values: props.btns,
  965. });
  966. },
  967. render: function () {
  968. DBG && console.log('DBG::P5UI__TableAjaxSpecialFilters::render (ns:'+this.props.namespace+')', { props: this.props, state: this.state });
  969. return h('div', {}, Object.keys(this.props.specialFilters).map(this.renderSpecialFilter))
  970. }
  971. });
  972. global['P5UI__TableAjaxFieldCheckboxSearch'] = createReactClass({
  973. // props.namespace: PropTypes.string.isRequired
  974. // props.fieldName: PropTypes.string.isRequired
  975. // props.store: Redux store with state: { isLoading bool, selected array of strings }
  976. // props.actions: Redux store actions
  977. getStateFromStore: function () {
  978. var state = this.props.store.getState();
  979. // selected = || 2 // 0 - unchecked, 1 - checked, 2 - indeterminate
  980. var selected = '';
  981. if (state.filter.has(this.props.fieldName)) {
  982. selected = state.filter.get(this.props.fieldName)
  983. }
  984. return {
  985. disabled: this.props.disabled ? true : false,
  986. selected: selected,
  987. active: ('YES' === selected || 'NO' === selected),
  988. // isLoading: (-1 !== state.loading.indexOf(this.props.fieldName)),
  989. // checked: (-1 !== state.selected.indexOf(this.props.fieldName))
  990. };
  991. },
  992. getInitialState: function() {
  993. return this.getStateFromStore();
  994. },
  995. componentDidMount: function () {
  996. DBG && console.log('DBG::P5UI__TableAjaxFieldCheckboxSearch::componentDidMount (f:'+this.props.fieldName+')');
  997. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  998. },
  999. componentWillUnmount: function () {
  1000. this.unsubscribe()
  1001. },
  1002. storeUpdated: function () {
  1003. DBG && console.log('DBG::P5UI__TableAjaxFieldCheckboxSearch::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
  1004. this.setState(this.getStateFromStore())
  1005. },
  1006. shouldComponentUpdate: function (nextProps, nextState) {
  1007. DBG && console.log('DBG::P5UI__TableAjaxFieldCheckboxSearch::shouldComponentUpdate (f:'+this.props.fieldName+')', { state: this.state, nextState});
  1008. return (
  1009. this.state.disabled !== nextState.disabled
  1010. || this.state.selected !== nextState.selected
  1011. );
  1012. },
  1013. handleChange: function (selected) { // selected: 0 - not checked, 1 - checked, 2 - indeterminate
  1014. DBG && console.log('DBG::P5UI__TableAjaxFieldCheckboxSearch::handleChange (f:'+this.props.fieldName+')', { selected: selected, state: this.state });
  1015. if (0 === selected) {
  1016. this.props.store.dispatch( this.props.actions.setFilter(this.props.fieldName, 'NO') );
  1017. } else if (1 === selected) {
  1018. this.props.store.dispatch( this.props.actions.setFilter(this.props.fieldName, 'YES') );
  1019. } else if (2 === selected) {
  1020. this.props.store.dispatch( this.props.actions.setFilter(this.props.fieldName, '') );
  1021. }
  1022. },
  1023. mapSelectedToValue: function (selected) {
  1024. switch (selected) {
  1025. case 'YES': return 1;
  1026. case 'NO': return 0;
  1027. default: return 2;
  1028. }
  1029. },
  1030. render: function () {
  1031. DBG && console.log('DBG::P5UI__TableAjaxFieldCheckboxSearch::render (f:'+this.props.fieldName+')', { props: this.props, state: this.state, state_sel: this.state.selected, sel: this.mapSelectedToValue(this.state.selected) });
  1032. return h('div',
  1033. {
  1034. style: {
  1035. boxSizing: 'border-box', width: '100%', height: '21px', padding: '0 5px', borderTop: 0,
  1036. borderBottom: '2px solid ' + ( this.state.active ? '#00ACCC' : 'transparent' ),
  1037. },
  1038. }, [
  1039. h(p5UI__FieldCheckboxSearch, {
  1040. size: 19,
  1041. color: '#888',
  1042. staticLabel: ["Pokaż:", "wszystkie,", "wybrane,", "niewybrane"].join("\n"),
  1043. fieldName: this.props.fieldName,
  1044. selected: this.mapSelectedToValue(this.state.selected),
  1045. onChange: this.handleChange
  1046. // checked: this.state.checked,
  1047. // disabled: this.state.disabled,
  1048. // isLoading: this.state.isLoading,
  1049. }),
  1050. ]
  1051. );
  1052. }
  1053. });
  1054. global['p5UI__FieldInputFilterSearch'] = createReactClass({
  1055. // props.fieldName: PropTypes.string.isRequired
  1056. // props.type: PropTypes.string.isRequired
  1057. // props.store: Redux store with state: { }
  1058. // props.actions: Redux store actions
  1059. // props.disabled: PropTypes.bool
  1060. // props.lagacyProps: PropTypes.object
  1061. getStateFromStore: function () {
  1062. var storeState = this.props.store.getState();
  1063. return {
  1064. value: storeState.filter.get(this.props.fieldName) || '',
  1065. active: storeState.filter.has(this.props.fieldName)
  1066. };
  1067. },
  1068. getInitialState: function() {
  1069. return this.getStateFromStore();
  1070. },
  1071. componentDidMount: function () {
  1072. DBG && console.log('DBG::p5UI__FieldInputFilterSearch::componentDidMount (f:'+this.props.fieldName+')');
  1073. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  1074. },
  1075. componentWillUnmount: function () {
  1076. this.unsubscribe()
  1077. },
  1078. storeUpdated: function () {
  1079. DBG && console.log('DBG::p5UI__FieldInputFilterSearch::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
  1080. this.setState(this.getStateFromStore())
  1081. },
  1082. shouldComponentUpdate: function (nextProps, nextState) {
  1083. DBG && console.log('DBG::p5UI__FieldInputFilterSearch::shouldComponentUpdate (f:'+this.props.fieldName+')', { state: this.state, nextState});
  1084. return (
  1085. this.state.value !== nextState.value
  1086. || this.state.active !== nextState.active
  1087. );
  1088. },
  1089. handleChange: function (event) { // handleChange: function (event) {
  1090. var value = event.target.value;
  1091. DBG && console.log('DBG::p5UI__FieldInputFilterSearch::handleChange (f:'+this.props.fieldName+')', { value });
  1092. this.setState({ value: value });
  1093. this.props.onChange(this.props.fieldName, value);
  1094. // this.props.store.dispatch( this.props.actions.toggle( this.props.namespace, this.props.primaryKey, checked ) )
  1095. },
  1096. render: function () {
  1097. DBG && console.log('DBG::p5UI__FieldInputFilterSearch::render (f:'+this.props.fieldName+',v:'+this.state.value+')', { props: this.props, state: this.state });
  1098. switch (this.props.type) {
  1099. case "number":
  1100. case "date":
  1101. case "bool":
  1102. case "p5:price":
  1103. case "p5:www_link":
  1104. case "p5:string":
  1105. case "string": return this.renderInput();
  1106. case "special": return this.renderEmpty();
  1107. case "simpleLink": return this.renderEmpty();
  1108. case "geom": return this.renderInput();
  1109. case "none": return this.renderEmpty();
  1110. case "ref": return this.renderEmpty();
  1111. default: return this.renderEmpty();
  1112. }
  1113. },
  1114. renderEmpty: function () {
  1115. return h('div', {}, " ");
  1116. },
  1117. renderInput: function () {
  1118. return h('input', {
  1119. className: "filter", // + ( this.state.active ? " filter-active" : "" ),
  1120. placeholder: !this.props.disabled ? "%" : "",
  1121. type: "text",
  1122. disabled: this.props.disabled || false,
  1123. style: {
  1124. boxSizing: 'border-box', width: '100%', height: '21px', borderTop: 0,
  1125. borderBottom: '2px solid ' + ( this.state.active ? '#00ACCC' : 'transparent' ),
  1126. },
  1127. value: this.state.value,
  1128. onChange: this.handleChange
  1129. });
  1130. }
  1131. });
  1132. global['p5UI__TableAjaxClearAllFilters'] = createReactClass({
  1133. // props.store: Redux store with state: { }
  1134. // props.actions: Redux store actions
  1135. getStateFromStore: function () {
  1136. var storeState = this.props.store.getState();
  1137. return {
  1138. isFiltersEmpty: ( 0 === storeState.filter.size && 0 === storeState.specialFilter.size )
  1139. };
  1140. },
  1141. getInitialState: function() {
  1142. return this.getStateFromStore();
  1143. },
  1144. componentDidMount: function () {
  1145. DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::componentDidMount (f:'+this.props.fieldName+')');
  1146. this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
  1147. },
  1148. componentWillUnmount: function () {
  1149. this.unsubscribe()
  1150. },
  1151. storeUpdated: function () {
  1152. DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
  1153. this.setState(this.getStateFromStore())
  1154. },
  1155. // shouldComponentUpdate: function (nextProps, nextState) {
  1156. // DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::shouldComponentUpdate (f:'+this.props.fieldName+')', { state: this.state, nextState});
  1157. // return (
  1158. // this.state.value !== nextState.value
  1159. // || this.state.active !== nextState.active
  1160. // );
  1161. // },
  1162. handleClick: function (event) {
  1163. DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::handleClick (clearAllFilters)');
  1164. this.props.store.dispatch( this.props.actions.clearAllFilters() )
  1165. },
  1166. render: function () {
  1167. DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::render (clearAllFilters)', { props: this.props, state: this.state });
  1168. return h('i', {
  1169. title: this.props.title || "Kasuj wszystkie filtry",
  1170. className: "glyphicon glyphicon-remove",
  1171. style: Object.assign(
  1172. {
  1173. opacity: '0.5',
  1174. lineHeight: '20px',
  1175. padding: '0 3px',
  1176. cursor: 'pointer',
  1177. },
  1178. this.state.isFiltersEmpty ? { color: '#777' } : { color: '#f00' }
  1179. ),
  1180. onClick: this.handleClick
  1181. });
  1182. }
  1183. });
  1184. var TableAjax = function() {
  1185. var priv = {}; //private api
  1186. var publ = {}; //public api
  1187. priv.options = {};
  1188. var defaults = {
  1189. namespace: '',
  1190. url: '', //webservice url
  1191. urlPost: false, //use POST instead of GET
  1192. selectAllByFilterUrl: '',
  1193. getCsvTheGeomAjaxUrl: '',
  1194. removeTheGeomAjaxUrl: '',
  1195. moreFunctionsCellAjaxUrl: '',
  1196. editInlineSaveUrl: '',
  1197. theGeomSaveUrl: '',
  1198. pageSizeSave: '',
  1199. hiddenColsSaveUrl: '',
  1200. editInlineUrl: '',
  1201. addUserTableFilterAjaxUrl: '',
  1202. rmUserTableFilterAjaxUrl: '',
  1203. hasAdditionalLayers: 0,
  1204. labelHtml: '',
  1205. debug: false, //prints debug info to console
  1206. filter: false, //show filter row
  1207. filterInit: false,// init filters data
  1208. forceFilterInit: false,
  1209. columnPicker: false, //show columnpicker
  1210. checkboxes: false, //show body checkboxes
  1211. actions: '', //holds action links
  1212. pageSize: 10, //current pagesize
  1213. pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
  1214. hidePagerOnEmpty: false, //removes pager if no rows
  1215. types: { //type specific options
  1216. string: {},
  1217. number: {},
  1218. bool: {},
  1219. date: {}
  1220. },
  1221. rowFunctions: false,
  1222. tblFunctions: false,
  1223. specialFilterFunctions: false,
  1224. filtersClean: false,
  1225. router: false,
  1226. longDesc: false,
  1227. exportFields: [],
  1228. mapEditor: false, // mapEditor visible or not
  1229. mapEditorContainer: 'window' // 'window' or 'dock'
  1230. };
  1231. var _uiNodeCont; // container holding table
  1232. var _uiNodeSelectedInfo;
  1233. var _uiNodeSpecialFilters;
  1234. var _uiNode$Table; // the table node
  1235. var _head; // table header
  1236. var _headSort; // table header sorting row
  1237. var _headFilter; // table header columns filter row
  1238. var _headSpecialFilter; // table header special filter row
  1239. var _bodyNode; // table body
  1240. var _body; // TODO: table body need render?
  1241. var _foot; // table footer
  1242. var _inlineEditBox; // inline edit box with form
  1243. var _popoverCell; // inline popover cell
  1244. var _popoverCellCurrent; // inline popover cell
  1245. var _popoverCellAjaxXhr;
  1246. var _mapEditor; // map editor node
  1247. var _mapEditorWrap; // map editor wrapper node
  1248. var _mapEditorDialog; // map editor jquery ui dialog node
  1249. var _state = {};// state - to replace variables below (date, ...)
  1250. var _data; //columns and rows
  1251. var _totalPages; // total pages
  1252. var _currDpOp; // clicked datetimepicker operator
  1253. var _filterTimeout; // timer for delayed filtering
  1254. var _checkToggleChecked = false; // check-all toggle state
  1255. var _exportFieldsSelect = {};
  1256. var _tableWidth;
  1257. var _fieldWidgets = {};
  1258. /*
  1259. initialize the plugin.
  1260. */
  1261. priv.init = function() {
  1262. _uiNodeCont = priv.options.id;
  1263. _state = {};// init state
  1264. _state.page = 1;
  1265. _state.specialFilters = {};
  1266. { // init events
  1267. jQuery(_uiNodeCont).on('TableAjax:render', priv.onRender);
  1268. jQuery(window).on('resize', priv.onWindowResize)
  1269. }
  1270. priv.initialRender();// set up _uiNode$...
  1271. priv.options.types.string = ((priv.options.types || {}).string || {});
  1272. priv.options.types.number = ((priv.options.types || {}).number || {});
  1273. priv.options.types.bool = ((priv.options.types || {}).bool || {});
  1274. priv.options.types.date = ((priv.options.types || {}).date || {});
  1275. if (priv.options.mapEditorContainer != 'dock'
  1276. && priv.options.mapEditorContainer != 'window') {
  1277. priv.options.mapEditorContainer = 'window';
  1278. }
  1279. if (priv.options.exportFields) {
  1280. $.each(priv.options.exportFields, function(ind, col) {
  1281. _exportFieldsSelect[col] = true;
  1282. });
  1283. }
  1284. _state._forceFilterQuery = p5Utils__objectToQueryWithKeyPrefix(priv.options.forceFilterInit, 'f_')
  1285. var filterStore = createFilterStoreWithInitialData(priv.options.filterInit || {});
  1286. priv.options.filterStore = createStoreWithThunkMiddleware(filterStore)
  1287. priv.options.filterActions = filterActions()
  1288. // priv.options._filterState = Object.assign({}, priv.options.filterStore.getState())
  1289. var curFilterState = priv.options.filterStore.getState()
  1290. _state._filterQuery = p5Utils__mapToQueryWithKeyPrefix(curFilterState.filter, 'f_')
  1291. _state._specialFilterQuery = p5Utils__mapToQueryWithKeyPrefix(curFilterState.specialFilter, 'sf_')
  1292. _state._currSortCol = curFilterState.currSortCol;
  1293. _state._currSortFlip = curFilterState.currSortFlip;
  1294. DBG && console.log('TODO:INIT: ', { _state });
  1295. priv.options.filterStore.subscribe(function () {
  1296. curState = priv.options.filterStore.getState()
  1297. var curFilterQuery = p5Utils__mapToQueryWithKeyPrefix(curState.filter, 'f_')
  1298. var curSpecialFilterQuery = p5Utils__mapToQueryWithKeyPrefix(curState.specialFilter, 'sf_')
  1299. var needFetchData = (
  1300. curFilterQuery !== _state._filterQuery
  1301. || curSpecialFilterQuery !== _state._specialFilterQuery
  1302. || curState.currSortCol !== _state._currSortCol
  1303. || curState.currSortFlip !== _state._currSortFlip
  1304. );
  1305. DBG && console.log('TODO:filtersUpdated - FETCH_DATA: ', { _state, curState });
  1306. _state._filterQuery = curFilterQuery;
  1307. _state._specialFilterQuery = curSpecialFilterQuery;
  1308. _state._currSortCol = curState.currSortCol;
  1309. _state._currSortFlip = curState.currSortFlip;
  1310. if (needFetchData) {
  1311. DBG && console.log('TODO:filtersUpdated - FETCH_DATA: ', { curFilterQuery, curSpecialFilterQuery });
  1312. priv.loadPage(0)
  1313. }
  1314. })
  1315. if (priv.options.checkboxes) {
  1316. priv.options.selectedStore = createStoreWithThunkMiddleware(selectedStore)
  1317. priv.options.selectedActions = selectedActions(idContext = priv.options.checkboxIdContext)
  1318. if (_uiNodeSelectedInfo) { // must run after priv.initialRender(); - _uiNodeSelectedInfo must exists
  1319. ReactDOM.render(
  1320. h(P5UI__TableAjaxSelectedInfo, {
  1321. namespace: priv.options.namespace,
  1322. store: priv.options.selectedStore,
  1323. actions: priv.options.selectedActions,
  1324. onSelectAllMatching: function () {
  1325. var filterQuery = '';
  1326. filterQuery += (_state._filterQuery) ? "&" + _state._filterQuery : "";
  1327. filterQuery += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
  1328. filterQuery += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
  1329. priv.options.selectedStore.dispatch( priv.options.selectedActions.selectAllMatchingFilter(priv.options.namespace, filterQuery) );
  1330. }
  1331. }),
  1332. _uiNodeSelectedInfo
  1333. );
  1334. }
  1335. } else {
  1336. if (_uiNodeSelectedInfo) {
  1337. // jQuery('<a href="'+window.location.href+'&TEST_CHECKBOX=1'+'">.</a>').appendTo(_uiNodeSelectedInfo);
  1338. jQuery('<a href="'+window.location.href+'">.</a>').appendTo(_uiNodeSelectedInfo);
  1339. }
  1340. }
  1341. if (location.hash) {
  1342. priv.options.router()
  1343. } else {
  1344. priv.update(priv.options.router)
  1345. }
  1346. if (typeof priv.options.router == "function") {
  1347. $(window).bind('hashchange', function() {
  1348. priv.options.router.apply(this);
  1349. });
  1350. }
  1351. };
  1352. priv.onRender = function(e) {
  1353. if (priv.options.debug || DBG) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
  1354. // console.log("priv.onRender arguments:", arguments);
  1355. // console.trace();
  1356. if (arguments.length > 1) {
  1357. for (var i=1; i<arguments.length; i++) {
  1358. switch (arguments[i]) {
  1359. case 'head': _head = undefined; break;
  1360. case 'body': _body = undefined; break;
  1361. case 'foot': _foot = undefined; break;
  1362. case 'foot_pagination': {
  1363. priv.renderFooterInfo();
  1364. priv.renderFooterPagination();
  1365. priv.renderFooterPageSizes();
  1366. }
  1367. break;
  1368. case 'footer__toolbar__info': priv.renderFooterInfo(); break;
  1369. case 'footer__toolbar__pagination': priv.renderFooterPagination(); break;
  1370. case 'footer__toolbar__pagesizes': priv.renderFooterPageSizes(); break;
  1371. case 'foot__columnPicker': priv.renderFooterColumnPicker(); break;
  1372. case 'head__specialFilters': priv.renderHeadSpecialFilters(); break;
  1373. }
  1374. }
  1375. priv.renderTable();
  1376. priv.onWindowResize();
  1377. {// activate saveBtn if some columns hidden
  1378. var selectedFilter = priv.modelColFilter_getSelected();
  1379. if (null === selectedFilter) {
  1380. priv.modelColFilter_getSaveBtn().prop("disabled", false)
  1381. } else {
  1382. priv.modelColFilter_getSaveBtn().prop("disabled", true)
  1383. }
  1384. }
  1385. }
  1386. };
  1387. priv.onWindowResize = function() {
  1388. var stickyCol1Width = priv.getStickyCol1Width();
  1389. var stickyCol2Width = priv.getStickyCol2Width();
  1390. var stickyCol3Width = priv.getStickyCol3Width();
  1391. var contW = jQuery(_uiNodeCont).parent().width();
  1392. var colsW = stickyCol1Width + stickyCol2Width + stickyCol3Width;
  1393. jQuery(_uiNodeCont).css({width:'' + (contW - colsW) + 'px'})//, marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
  1394. var wh = jQuery(window).height(); // returns height of browser viewport
  1395. var dh = jQuery(document).height(); // returns height of HTML document (same as pageHeight in screenshot)
  1396. if (dh > wh) {
  1397. jQuery(_uiNodeCont).doubleScroll()
  1398. jQuery(_uiNodeCont).prev('.doubleScroll-scroll-wrapper').css({float: 'right', display:'block'})
  1399. } else {
  1400. jQuery(_uiNodeCont).prev('.doubleScroll-scroll-wrapper').css({display:'none'})
  1401. }
  1402. }
  1403. priv.getStickyCol1Width = function () { return (12 + 3) * 4 + 2 * 5 + 1; }
  1404. priv.getStickyCol2Width = function () { return (priv.options.checkboxes) ? 20 + 2 * 5 + 1 : 0; }
  1405. priv.getStickyCol3Width = function () { return 50 + 2 * 5 + 1; }
  1406. priv.getStickyColsSumWidth = function () { return priv.getStickyCol1Width() + priv.getStickyCol2Width() + priv.getStickyCol3Width(); }
  1407. priv.initialRender = function() {
  1408. _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiNodeCont);
  1409. _head = $('<thead></thead>').prependTo(_uiNode$Table);
  1410. _headSort = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head);
  1411. _headFilter = $('<tr class="filter tblAjax__head__filter"></tr>').appendTo(_head);
  1412. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  1413. $('<tfoot></tfoot>').insertAfter(_bodyNode);
  1414. _foot = $('<div class="foot tblAjax__footer"></div>').insertAfter(_uiNodeCont);
  1415. var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar"></div>').appendTo(_foot);
  1416. $('<span class="tblAjax__footer__toolbar__info"></span>').appendTo(footToolbar);
  1417. $('<span class="tblAjax__footer__toolbar__pagination"></span>').appendTo(footToolbar);
  1418. $('<span class="tblAjax__footer__toolbar__pagesizes"></span>').appendTo(footToolbar);
  1419. $('<span class="tblAjax__footer__toolbar__columnPicker"></span>').appendTo(footToolbar);
  1420. $('<span class="tblAjax__footer__toolbar__functions"></span>').appendTo(footToolbar);
  1421. $('<span class="tblAjax__footer__toolbar__export"></span>').appendTo(footToolbar);
  1422. _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
  1423. _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
  1424. _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
  1425. $('<div class="tblAjax__inlineEditBox"></div>').insertAfter(_foot);
  1426. _uiNodeSelectedInfo = document.createElement('div')
  1427. _uiNodeSpecialFilters = document.createElement('div') // .tblAjax__head__specialFilter
  1428. var topWrap = document.createElement('div')
  1429. var topWrapLeft = document.createElement('div')
  1430. var topWrapRight = document.createElement('div')
  1431. topWrap.appendChild(topWrapLeft)
  1432. topWrap.appendChild(topWrapRight)
  1433. topWrapLeft.style.width = '' + priv.getStickyColsSumWidth() + 'px'
  1434. topWrapLeft.style.padding = '4px'
  1435. topWrapLeft.style.float = 'left'
  1436. topWrapLeft.style.fontSize = '12px'
  1437. topWrapLeft.style.lineHeight = '22px'
  1438. topWrapRight.style.float = 'left'
  1439. topWrapRight.style.padding = '4px'
  1440. topWrapLeft.appendChild(_uiNodeSelectedInfo)
  1441. topWrapRight.appendChild(_uiNodeSpecialFilters)
  1442. _uiNodeCont.parentNode.insertBefore(topWrap, _uiNodeCont)
  1443. priv.renderInlineEditBox();// .tblAjax__inlineEditBox
  1444. _foot = _head = _body = _headSort = _headFilter = undefined;// TODO: refactor
  1445. };
  1446. priv.renderTable = function() {
  1447. if (!_state.colsSorted) return;
  1448. if (!_head) {
  1449. _headSort = _headFilter = _headSpecialFilter = undefined;
  1450. _head = _uiNode$Table.find('thead');
  1451. }
  1452. if (!_headSort) priv.renderTableTheadSort();
  1453. if (!_headFilter && priv.options.filter) {
  1454. priv.renderTableTheadFilter();
  1455. _headFilter = true;
  1456. }
  1457. if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
  1458. priv.renderHeadSpecialFilters();
  1459. _headSpecialFilter = true;
  1460. }
  1461. if (!_body) {
  1462. _uiNode$Table.find('tbody').remove();
  1463. _bodyNode = $('<tbody></tbody>').insertAfter(_head);
  1464. // find out what rows to show next...
  1465. var rowsAdded = 0;
  1466. // slice out the chunk of data we need and create rows
  1467. $.each(_data.rows, function(index, props) {
  1468. var rowNode = priv.renderRow(props);
  1469. if (rowNode) rowNode.appendTo(_bodyNode);
  1470. rowsAdded++;
  1471. if (rowsAdded >= priv.options.pageSize) { // enough rows created
  1472. return false;
  1473. }
  1474. });
  1475. if (_state.page == 1) {
  1476. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  1477. }
  1478. if (_state.page == _totalPages) { // pad with empty rows if we're at last page.
  1479. while (rowsAdded < priv.options.pageSize) {
  1480. var rowNode = priv.renderRowEmptyNode();
  1481. if (rowNode) rowNode.appendTo(_bodyNode);
  1482. rowsAdded++;
  1483. }
  1484. }
  1485. }
  1486. if (!_foot) {
  1487. priv.renderTableTfoot();
  1488. priv.renderFooter();
  1489. }
  1490. _foot = $(_uiNodeCont).next('.foot');
  1491. var stickyCol1Width = priv.getStickyCol1Width();
  1492. var stickyCol2Width = priv.getStickyCol2Width();
  1493. var stickyCol3Width = priv.getStickyCol3Width();
  1494. if (undefined === _tableWidth) {
  1495. _tableWidth = true;
  1496. var contW = jQuery(_uiNodeCont).width();
  1497. var th1 = _uiNode$Table.find('.stickyCol1:first');
  1498. var th2 = th1.next();
  1499. var th1W = th1.innerWidth();
  1500. var th2W = 50 + 2 * 5;//th2.innerWidth();
  1501. var colsW = stickyCol1Width + stickyCol2Width + stickyCol3Width;
  1502. jQuery(_uiNodeCont).css({
  1503. width: '' + (contW - colsW) + 'px',
  1504. marginLeft: '' + colsW + 'px',
  1505. minHeight: '360px',
  1506. overflowX: 'scroll',
  1507. overflowY: 'visible',
  1508. paddingBottom: '1px',
  1509. clear: 'both',
  1510. });
  1511. }
  1512. _uiNode$Table.find('.stickyCol1').css({
  1513. position: 'absolute',
  1514. left: '0',
  1515. top: 'auto',
  1516. width: '' + stickyCol1Width + 'px',
  1517. });
  1518. //_uiNode$Table.find('.filter').find('.stickyCol1').css({height:'34px'});
  1519. var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
  1520. _uiNode$Table.find('.sort').find('.stickyCol').css({height: sortStickyColHeight + 'px'});
  1521. var filterStickyColHeight = _uiNode$Table.find('.filter').find('th:last').outerHeight() + 1;
  1522. _uiNode$Table.find('.filter').find('.stickyCol').css({height: filterStickyColHeight + 'px'});
  1523. if (priv.options.checkboxes) _uiNode$Table.find('.stickyCol2').css({
  1524. position: 'absolute',
  1525. left: '' + (stickyCol1Width) + 'px',
  1526. top: 'auto',
  1527. width: '' + stickyCol2Width + 'px',
  1528. borderRight: '1px solid silver',
  1529. overflow: 'hidden'
  1530. });
  1531. _uiNode$Table.find('.stickyCol3').css({
  1532. position: 'absolute',
  1533. left: '' + (stickyCol1Width + stickyCol2Width) + 'px',
  1534. top: 'auto',
  1535. width: '' + stickyCol3Width + 'px',
  1536. borderRight: '1px solid silver',
  1537. overflow: 'hidden'
  1538. });
  1539. _uiNode$Table.find('tbody').find('.stickyCol').css({
  1540. height: '' + (29 + 1) + 'px',
  1541. });
  1542. if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
  1543. $('.btn-toolbar', _foot).remove();
  1544. }
  1545. if (priv.options.debug || DBG) console.log('table created');
  1546. if (typeof priv.options.tableCreated == 'function') {
  1547. priv.options.tableCreated.call(_uiNode$Table.get(0), {table: _uiNode$Table.get(0)});
  1548. }
  1549. };
  1550. // TODO: priv.renderFieldWidget_InlineEdit = function(fldName, value) {}
  1551. // TODO: priv.renderFieldWidget_FormField = function(fldName, value) {}
  1552. // @usage: priv.renderFieldWidget_TableCell(fldName, val, rowPK, row)
  1553. priv.renderFieldWidget_TableCell = function(fldName, value, rowPK, row) {
  1554. var renderFieldAsTableCell = priv.getFieldWidget_TableCell(fldName);
  1555. if (!renderFieldAsTableCell) return null;
  1556. return renderFieldAsTableCell(value, rowPK, row);
  1557. };
  1558. priv.registerFieldWidget = function(type, fldName, fieldProps) {
  1559. var fieldWidget = null;
  1560. switch (type) {
  1561. case "date":// @return Element - TODO: not used yet
  1562. fieldWidget = (function(fldName, fieldProps) {
  1563. var _fieldName = fldName,
  1564. _fieldProps = fieldProps;
  1565. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1566. return function(val, fieldPK, row) {
  1567. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1568. return val;
  1569. }
  1570. }(fldName, fieldProps));
  1571. break;
  1572. case "bool":// @return Element - TODO: not used yet
  1573. fieldWidget = (function(fldName, fieldProps) {
  1574. var _fieldName = fldName,
  1575. _fieldProps = fieldProps;
  1576. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1577. return function(val, fieldPK, row) {
  1578. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1579. fldNode = document.createElement('input');
  1580. fldNode.setAttribute('type', 'checkbox');
  1581. if (val) fldNode.setAttribute('checked', 'checked');
  1582. fldNode.setAttribute('disabled', 'disabled');
  1583. fldNode.appendChild(document.createTextNode(val));
  1584. return fldNode;
  1585. }
  1586. }(fldName, fieldProps));
  1587. break;
  1588. case "number":// @return String - TODO: not used yet
  1589. fieldWidget = (function(fldName, fieldProps) {
  1590. var _fieldName = fldName,
  1591. _fieldProps = fieldProps,
  1592. _fractionDigits = _.get(_fieldProps, 'fractionDigits', 2);
  1593. // console.log('FieldWidget: generate function to render field('+_fieldName+') _fractionDigits('+_fractionDigits+')', fieldProps);
  1594. return function(val, fieldPK, row) {
  1595. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1596. if ('' === val) return null; // is nullable
  1597. if ('*****' === val) return val
  1598. // enumeration
  1599. // fractionDigits
  1600. // maxExclusive
  1601. // maxInclusive
  1602. // minExclusive
  1603. // minInclusive
  1604. // pattern
  1605. // totalDigits
  1606. // whiteSpace
  1607. val = Number(val);
  1608. return ((val || 0) % 1 === 0)? val : val.toFixed(_fractionDigits);
  1609. }
  1610. }(fldName, fieldProps));
  1611. break;
  1612. case "string":// @return String
  1613. fieldWidget = (function(fldName, fieldProps) {
  1614. var _fieldName = fldName,
  1615. _fieldProps = fieldProps,
  1616. _format = _.get(_fieldProps, 'format', '{0}');
  1617. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1618. return function(val, fieldPK, row) {
  1619. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1620. return p5Utils__format(_format, [val]);
  1621. }
  1622. }(fldName, fieldProps));
  1623. break;
  1624. case "p5:price":// @return String
  1625. fieldWidget = (function(fldName, fieldProps) {
  1626. var _fieldName = fldName,
  1627. _fieldProps = fieldProps,
  1628. _format = _.get(_fieldProps, 'format', '<span style="text-align:right">{0}</span>');
  1629. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1630. return function(val, fieldPK, row) {
  1631. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1632. return p5Utils__format(_format, [val]);
  1633. }
  1634. }(fldName, fieldProps));
  1635. break;
  1636. case "p5:string":// @return String
  1637. fieldWidget = (function(fldName, fieldProps) {
  1638. var _fieldName = fldName;
  1639. var _fieldProps = fieldProps;
  1640. var _formatByValue = _.get(_fieldProps, 'formatByValue', null);
  1641. var _aliasMap = _.get(_fieldProps, 'aliasMap', null);
  1642. return function(val, fieldPK, row) {
  1643. if (_formatByValue && val in _formatByValue) {
  1644. val = p5Utils__format(_formatByValue[val], [val])
  1645. // console.log('p5:string value', val, '_aliasMap', _aliasMap)
  1646. if (_aliasMap) {
  1647. Object.keys(_aliasMap).map(function (mapKey) {
  1648. var mapField = _aliasMap[mapKey]
  1649. if (undefined !== row[mapField]) {
  1650. val = val.replace(new RegExp('\{' + mapKey + '\}', 'g'), row[mapField]);
  1651. }
  1652. })
  1653. }
  1654. }
  1655. return val;
  1656. }
  1657. }(fldName, fieldProps));
  1658. break;
  1659. case "p5:www_link":// @return Element
  1660. fieldWidget = (function(fldName, fieldProps) {
  1661. var _fieldName = fldName,
  1662. _fieldProps = fieldProps;
  1663. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1664. return function(val, fieldPK, row) {
  1665. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1666. var link = '',
  1667. a = null,
  1668. dbg = false;
  1669. if (!val.length) return '';
  1670. if ('index.php' == val.substr(0, 9) || 'procesy5.php' == val.substr(0, 12)) {
  1671. link = window.location.protocol + '//' + window.location.hostname
  1672. link += window.location.pathname.split('/').slice(0, -1).join('/')
  1673. link += '/' + val
  1674. } else {
  1675. if ('http' == val.substr(0, 4)) link = val
  1676. //else if ('ftp' == val.substr(0, 3))
  1677. else link = 'http://' + val
  1678. }
  1679. var linkErrors = validate({www_link: link}, {www_link: {url: true}});
  1680. if (linkErrors) {
  1681. // if(dbg)console.log('linkErrors for (' + link +')', linkErrors);
  1682. return val;
  1683. }
  1684. fldNode = document.createElement('a');
  1685. fldNode.setAttribute('href', link);
  1686. fldNode.setAttribute('target', '_blank');
  1687. fldNode.appendChild(document.createTextNode(val));
  1688. return fldNode;
  1689. }
  1690. }(fldName, fieldProps));
  1691. break;
  1692. case "special":
  1693. fieldWidget = (function(fldName, fieldProps) {
  1694. var _fieldName = fldName;
  1695. var _fieldProps = fieldProps;
  1696. var _format = _.get(_fieldProps, 'format', '{0}');
  1697. var _aliasMap = _.get(_fieldProps, 'aliasMap', null);
  1698. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1699. return function(val, fieldPK, row) {
  1700. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps, 'row', row);
  1701. var format = _format;
  1702. if (_aliasMap) {
  1703. Object.keys(_aliasMap).map(function (mapKey) {
  1704. var mapField = _aliasMap[mapKey]
  1705. if (undefined !== row[mapField]) {
  1706. format = format.replace(new RegExp('\{' + mapKey + '\}', 'g'), row[mapField]);
  1707. }
  1708. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') _aliasMap:', _aliasMap, 'row['+mapField+']', row[mapField], 'converted val:', val);
  1709. })
  1710. }
  1711. return p5Utils__format(format, [val]);
  1712. }
  1713. }(fldName, fieldProps));
  1714. break;
  1715. case "simpleLink":
  1716. fieldWidget = (function(fldName, fieldProps) {
  1717. var _fieldName = fldName,
  1718. _fieldProps = fieldProps,
  1719. _format = _.get(_fieldProps, 'format', '{0}');
  1720. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1721. return function(val, fieldPK, row) {
  1722. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1723. var valLink = String(val);
  1724. if (undefined !== _fieldProps._tsRetId
  1725. && (0 === _fieldProps._tsRetId || '0' === _fieldProps._tsRetId || null === _fieldProps._tsRetId)
  1726. && undefined !== _fieldProps._tsSimpleLink) {
  1727. valLink = _fieldProps._tsSimpleLink.format;
  1728. $.each(_fieldProps._tsSimpleLink.aliasMap, function(i, v) {
  1729. // console.log('simpleLink aliasMap fldName:', fldName, 'i:', i, 'v:', v, 'row['+v+']', row[v], 'val', val, 'typeof val', typeof val);
  1730. if (undefined !== row[v]) {
  1731. var _itemValue = row[v];
  1732. if (fldName == 'LINK_PROBLEMS' && row[v]) _itemValue = _itemValue.replace(/"/g, '%22').replace(/&/g, '%26');
  1733. valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), _itemValue);
  1734. }
  1735. });
  1736. }
  1737. return p5Utils__format(_format, [valLink]);
  1738. }
  1739. }(fldName, fieldProps));
  1740. break;
  1741. case "gml:PolygonPropertyType":
  1742. case "gml:LineStringPropertyType":
  1743. case "gml:PointPropertyType":
  1744. case "p5Type:polygon":
  1745. case "p5Type:lineString":
  1746. case "p5Type:point":
  1747. case "geom":
  1748. fieldWidget = (function(fldName, fieldProps) {
  1749. var _fieldName = fldName,
  1750. _fieldProps = fieldProps,
  1751. _format = _.get(_fieldProps, 'format', '{0}');
  1752. // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
  1753. return function(val, fieldPK, row) {
  1754. // console.log('FieldWidget: run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
  1755. // console.log('FieldWidget: test priv', priv);
  1756. var node = jQuery('<span></span>');
  1757. node.TableAjaxGeomField({
  1758. recordID: fieldPK,
  1759. fieldValue: val,
  1760. hasValueClassName: 'cell-mapfld-hasValue',
  1761. linkClassNamePrefix: 'cell-mapfld',
  1762. linkSelectClassName: 'select',
  1763. linkSelectAddClassNames: 'glyphicon glyphicon-map-marker',
  1764. getCsvUrl: priv.options.getCsvTheGeomAjaxUrl,
  1765. linkGetCsvAddClassNames: 'glyphicon glyphicon-download',
  1766. linkRemoveClassName: 'remove',
  1767. linkRemoveAddClassNames: 'glyphicon glyphicon-remove',
  1768. onSelect: function(recordID, geomShape) {
  1769. if (priv.options.debug || DBG) console.log('recordID:', recordID, 'geomShape:', geomShape);
  1770. priv.mapEditorShow();
  1771. _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
  1772. },
  1773. onRemove: function(geomField, recordID, geomShape) {
  1774. if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
  1775. if (!recordID) return;
  1776. var selectedRecordId = recordID;
  1777. superagent
  1778. .post(priv.options.removeTheGeomAjaxUrl)
  1779. .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
  1780. .send({
  1781. ID: recordID,
  1782. namespace: priv.options.namespace
  1783. })
  1784. .set('Accept', 'application/json')
  1785. .end(function(err, res) {
  1786. if(priv.options.debug)console.log('DBG: res:', res, 'res.body:', res.body);
  1787. var payload;
  1788. if (err || !res.ok || 'application/json' !== res.type) {
  1789. payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
  1790. } else {
  1791. payload = {type: 'success', msg: res.body.msg || '', body: res.body};
  1792. }
  1793. p5UI__notifyAjaxCallback(payload);
  1794. var data = res.body;
  1795. if (data && data.record && data.record.the_geom) {
  1796. if (priv.options.debug || DBG) console.log('data.record.the_geom:2:', data.record.the_geom);
  1797. geomField.setValue(data.record.the_geom);
  1798. }
  1799. else if (data && data.record) {
  1800. if (priv.options.debug || DBG) console.log('data.record.the_geom:2:', data.record.the_geom);
  1801. geomField.setValue(data.record.the_geom);
  1802. }
  1803. _mapEditor.TableAjaxMapRefresh();
  1804. });
  1805. }
  1806. }
  1807. });
  1808. return node;
  1809. }
  1810. }(fldName, fieldProps));
  1811. break;
  1812. case "ref":
  1813. fieldWidget = (function(fldName, fieldProps) {
  1814. var _fieldName = fldName,
  1815. _fieldProps = fieldProps;
  1816. // console.log('FieldWidget: generate function to render field('+_fieldName+') fieldProps: ', fieldProps);
  1817. return function(val, fieldPK, row) {
  1818. // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value: ', val, ', fieldProps: ', fieldProps);
  1819. // if (val.length > 5) return '('+val.length+')' + printFirst5 + '...' => open more info
  1820. return _.map(val, function(v) {
  1821. if (!v || !v.xlink) return '';
  1822. var idRemote = v.xlink.split('.').pop()
  1823. var nsRemote = v.xlink.split(':').pop().split('.').shift()
  1824. var seLink = URI_BASE + 'index.php?_route=ViewTableAjax&namespace=' + fieldProps.xsdRefNsPrefix.replace(/__x3A__/g, '/') + '/' + nsRemote + '#EDIT/' + idRemote;
  1825. var wfsLink = fieldProps.xsdRefUri + '#' + fieldProps.xsdRefType + '.' + idRemote;
  1826. return '<a class="btn btn-xs btn-default" href="' + seLink + '" title="' + wfsLink + '">' + idRemote + '</a>';
  1827. }).join(' ');
  1828. }
  1829. }(fldName, fieldProps));
  1830. break;
  1831. }
  1832. _fieldWidgets[fldName] = fieldWidget;
  1833. };
  1834. priv.getFieldWidget_TableCell = function(fieldName) {
  1835. var props = _data.cols[fieldName],
  1836. type = null,
  1837. renderFieldAsTableCell = null;
  1838. if (!props) return null;
  1839. type = _.get(props, 'type');
  1840. if (!type) type = 'string';// TODO: throw Exception? / default string
  1841. renderFieldAsTableCell = _.get(_fieldWidgets, fieldName);
  1842. if (renderFieldAsTableCell) return renderFieldAsTableCell;
  1843. priv.registerFieldWidget(type, fieldName, props);
  1844. renderFieldAsTableCell = _.get(_fieldWidgets, fieldName);
  1845. if (!renderFieldAsTableCell) throw "Field type '" + type + "' not implemented";
  1846. return renderFieldAsTableCell;
  1847. };
  1848. priv.renderRow = function(props) {
  1849. var rowNode = $('<tr></tr>'),
  1850. rowPK = (_state.primaryKey in props) ? props[_state.primaryKey] : null,
  1851. cellNode,
  1852. columnName, columnProps, val, cellCnt, format, showTooltip, fldWidgetNode,
  1853. dbg = (priv.options.debug || DBG)
  1854. ;
  1855. // ondrop="drop_handler(event);" ondragover="dragover_handler(event);" ondragend="dragend_handler(event);"
  1856. rowNode.attr('ondrop', "p5TA_onDrop(event, '"+rowPK+"', '"+priv.options.namespace+"')")
  1857. rowNode.attr('ondragover', "p5TA_onDragOver(event, this, '"+rowPK+"', '"+priv.options.namespace+"')")
  1858. rowNode.attr('ondragend', "p5TA_onDragEnd(event, this, '"+rowPK+"', '"+priv.options.namespace+"')")
  1859. if (priv.options.rowFunctions || priv.options.filtersClean) {
  1860. cellNode = priv.renderCellRowFunctions(priv.options.rowFunctions, rowPK, props);
  1861. cellNode.addClass('text-right stickyCol stickyCol1');
  1862. cellNode.appendTo(rowNode);
  1863. }
  1864. //create checkbox
  1865. if (_state.primaryKey && priv.options.checkboxes) { // row checkbox cell
  1866. var checkable = props['checkable'] === false ? 'disabled' : '';
  1867. cellNode = $('<td class="stickyCol stickyCol2" style="padding:3px 5px"></td>').appendTo(rowNode);
  1868. ReactDOM.render(
  1869. h(P5UI__TableAjaxRowCheckbox, {
  1870. namespace: priv.options.namespace,
  1871. primaryKey: rowPK,
  1872. store: priv.options.selectedStore,
  1873. actions: priv.options.selectedActions
  1874. }),
  1875. cellNode.get(0)
  1876. );
  1877. }
  1878. if (_state.primaryKey) rowNode.data('unique', rowPK);
  1879. //create cells
  1880. for (var i = 0; i < _state.colsSorted.length; i++) {
  1881. columnName = _state.colsSorted[i];
  1882. columnProps = _data.cols[columnName];
  1883. val = '';
  1884. if (!columnProps) continue;
  1885. if (columnProps.hidden) continue;// TODO: "unique" is hidden
  1886. showTooltip = true;
  1887. val = props[columnName];
  1888. cellNode = $('<td></td>').appendTo(rowNode);
  1889. if (i === 1) cellNode.addClass('stickyCol stickyCol3');// primaryKey(ID)
  1890. if (i !== 1) cellNode.on('dblclick', {id:rowPK, col:columnName}, priv.rowDblClicked);
  1891. cellCnt = (i === 1)? '<div></div>' : '<span></span>';
  1892. cellCnt = $(cellCnt).appendTo(cellNode);// fix dblclick for copy
  1893. cellNode.data('column', columnName);
  1894. if (val === undefined) continue;
  1895. format = _.get(columnProps, 'format', '{0}');
  1896. // test use field widgets
  1897. fldWidgetNode = priv.renderFieldWidget_TableCell(columnName, val, rowPK, props);
  1898. if (fldWidgetNode || fldWidgetNode === 0) {
  1899. cellCnt.empty();
  1900. cellCnt.append(fldWidgetNode);
  1901. } else if (fldWidgetNode === '') {
  1902. cellCnt.empty();
  1903. } else {
  1904. console.log('TODO: !FieldWidget for row.pk('+rowPK+') col('+columnName+') typeof fldWidgetNode(' + (typeof fldWidgetNode) + ') columnProps', columnProps, 'fldWidgetNode', fldWidgetNode, 'value', props[columnName]);
  1905. }// test fld widgets
  1906. if (columnProps._tsRetId) {
  1907. showTooltip = false;
  1908. if (columnProps._tsRetId > 0) {
  1909. cellCnt.on('click', {id:rowPK, col:columnName, friendly:columnProps.friendly, value:p5Utils__format(format, [val])}, priv.popoverCellTypeSpecial);
  1910. }
  1911. }
  1912. if ('ref' === columnProps.type) showTooltip = false;
  1913. if ('ref' === columnProps.type) cellNode.css('padding', "3px")
  1914. if ('ref' === columnProps.type && (priv.options.debug || DBG)) console.log('renderRow rowPK('+rowPK+') columnProps', columnProps)
  1915. // if ('ref' === columnProps.type) cellNode.html('<a href="index.php?_route=ViewTableAjax' +
  1916. // '&namespace=' + columnProps.xsdRefNsPrefix.replace('__x3A__', '/') + '/' + columnProps.xsdRefType +
  1917. // '&backRefNS=' + priv.options.namespace +
  1918. // '&backRefPK=' + rowPK +
  1919. // '&backRefField=' + columnProps.column +
  1920. // '">przeglądaj</a>')
  1921. if ('ref' === columnProps.type) {
  1922. cellNode.html('<a onClick="return p5UI__tableAjaxOpenRefCell(' +
  1923. '\'' + columnProps.xsdRefNsPrefix.replace('__x3A__', '/') + '/' + columnProps.xsdRefType + '\', ' + // namespace
  1924. '\'' + priv.options.namespace + '\', ' + // backRefNS
  1925. '\'' + rowPK + '\', ' + // backRefPK
  1926. '\'' + columnProps.column + '\')' + // backRefField
  1927. '" ' +
  1928. 'href="index.php?_route=ViewTableAjax' +
  1929. '&namespace=' + columnProps.xsdRefNsPrefix.replace('__x3A__', '/') + '/' + columnProps.xsdRefType +
  1930. '&backRefNS=' + priv.options.namespace +
  1931. '&backRefPK=' + rowPK +
  1932. '&backRefField=' + columnProps.column +
  1933. '">przeglądaj</a>')
  1934. }
  1935. if (columnProps.xsdType && 'xsd:base64Binary' === columnProps.xsdType) {
  1936. cellCnt.empty();
  1937. if (val) {
  1938. cellCnt.append('<a target="_blank" href="wfs-data.php?SERVICE=WFS&VERSION=1.0.0&REQUEST=GetBlob&namespace='+priv.options.namespace+'&primaryKey='+rowPK+'&fieldName='+columnName+'">'+"otwórz"+'</a>');
  1939. } else {
  1940. cellCnt.append('<span style="color:silver" title="Brak danych">N/S;</span>');
  1941. }
  1942. }
  1943. if (i > 1 && priv.options.longDesc) {// TODO: use better check for columns: functions and pk
  1944. cellNode.addClass('tbl-short-txt');
  1945. if (showTooltip) {
  1946. cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
  1947. }
  1948. }
  1949. }
  1950. return rowNode;
  1951. };
  1952. priv.renderCellRowFunctions = function(rowFunctions, rowPK, rowProps) {
  1953. var cellNode = $('<td></td>'),
  1954. keys = Object.keys(rowFunctions),
  1955. total = keys.length,
  1956. moreFuncBtnNode,
  1957. moreFunctions = [],
  1958. idx
  1959. ;
  1960. if (priv.options.debug || DBG) console.log('TableAjax::renderCellRowFunctions: rowFunctions', rowFunctions);
  1961. idx = keys.indexOf('hist');
  1962. if (idx !== -1) {
  1963. histFunc = keys.splice(idx, 1);
  1964. keys.push('hist');
  1965. }
  1966. moreFunctions = keys.splice(3);
  1967. keys.forEach(function(key) {
  1968. var funObj = rowFunctions[key],
  1969. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: false})
  1970. ;
  1971. funcNode.appendTo(cellNode);
  1972. });
  1973. moreFuncBtnNode = $('<a href="#" style="margin:0 2px;text-decoration:none" title="Więcej funkcji dla rekordu nr '+rowPK+'" class="glyphicon glyphicon-menu-hamburger"> </a>');
  1974. moreFuncBtnNode.on('click', {rowPK: rowPK, rowFunctions: rowFunctions, more: moreFunctions}, priv.popoverCellMoreFunctions);
  1975. moreFuncBtnNode.appendTo(cellNode);
  1976. return cellNode;
  1977. };
  1978. priv.popoverCellMoreFunctions = function(e) {
  1979. e.preventDefault();
  1980. e.stopPropagation();
  1981. if (!e.data || !e.data.rowPK) {
  1982. if (priv.options.debug || DBG) console.log('NO data');
  1983. return false;
  1984. }
  1985. if (priv.options.debug || DBG) console.log('TableAjax::popoverCellMoreFunctions: rowPK', e.data.rowPK, 'moreFunctions', e.data.more, 'rowFunctions', e.data.rowFunctions);
  1986. var lastId = _popoverCell.data('rowid');
  1987. var lastCol = _popoverCell.data('col');
  1988. var rowPK = e.data.rowPK;
  1989. var moreFunctions = e.data.more;
  1990. var rowFunctions = e.data.rowFunctions;
  1991. var funcListNode;
  1992. if (lastId == e.data.rowPK && lastCol == 'moreFunctions') {
  1993. //_popoverCellCurrent.popover('toggle');
  1994. return;
  1995. }
  1996. if (_popoverCellCurrent) {
  1997. _popoverCellCurrent.popover('destroy');
  1998. }
  1999. _popoverCell.data('rowid', rowPK);
  2000. _popoverCell.data('col', 'rowFunctions');
  2001. _popoverCell.empty();
  2002. funcListNode = $('<ul class="list-unstyled popoverRowFunctions"></ul>').appendTo(_popoverCell);
  2003. moreFunctions.forEach(function(funcName) {
  2004. var funcItemNode = $('<li></li>').appendTo(funcListNode),
  2005. funObj = rowFunctions[funcName],
  2006. funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: true})
  2007. ;
  2008. funcNode.addClass('func_name-' + funcName);
  2009. funcItemNode.append(funcNode);
  2010. });
  2011. if (3 === priv.options.namespace.split('/').length) { // if namesapce is AntAcl [ and has ref fields or back ref ]
  2012. var funcItemNode = $('<li></li>').appendTo(funcListNode)
  2013. var funObj = {
  2014. ico: 'glyphicon glyphicon-random',
  2015. label: 'Przeglądaj powiązania',
  2016. href: 'index.php?_route=RefGraph&namespace=' + priv.options.namespace + '&primaryKey=' + rowPK,
  2017. // onclick: function (e) { // TODO: open in
  2018. // console.log('TODO: przeglądaj powiązania')
  2019. // }
  2020. }
  2021. var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true })
  2022. funcItemNode.append(funcNode);
  2023. }
  2024. _popoverCell.append('<div class="popoverCellContent" style="white-space:normal"></div>');
  2025. _popoverCellCurrent = jQuery(e.currentTarget);
  2026. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  2027. var opts = {
  2028. container: 'body',
  2029. placement: 'right',
  2030. trigger: 'click',
  2031. template: '',
  2032. html: true,
  2033. content: _popoverCell.html()
  2034. }
  2035. opts.template += '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">';
  2036. {
  2037. opts.template += '<div class="arrow"></div>';
  2038. //opts.template += '<h3 class="popover-title"></h3>';
  2039. opts.template += '<div style="display:block;position:relative;">';
  2040. {
  2041. opts.template += '<div class="popover-title">';
  2042. opts.template += '</div>';
  2043. opts.template += '<button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:8px;top:6px;">&times;</button>';
  2044. }
  2045. opts.template += '</div>';
  2046. opts.template += '<div class="popover-content"></div>';
  2047. }
  2048. opts.template += '</div>';
  2049. _popoverCellCurrent.popover(opts);
  2050. _popoverCellCurrent.on('shown.bs.popover', function(e) {
  2051. if (!_popoverCellCurrent) return;
  2052. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  2053. if (!popoverNodeId) return;
  2054. var popover$Node = jQuery('#' + popoverNodeId);
  2055. if (!popover$Node.length) return;
  2056. var arrow$Node = popover$Node.children('.arrow');
  2057. if (arrow$Node.length) {
  2058. var posTop = parseFloat(arrow$Node.css('top'));
  2059. arrow$Node.css('top', '' + posTop + 'px')
  2060. }
  2061. popover$Node.find('.popoverCellContent').html('<p class="text-muted">Pobieranie funkcji...<p>');
  2062. priv.ajaxLoadMoreFunctionsCell(rowPK);
  2063. });
  2064. _popoverCellCurrent.popover('show');
  2065. return;
  2066. };
  2067. priv.ajaxLoadMoreFunctionsCell = function(rowPK) {
  2068. var dbg = (priv.options.debug || DBG);
  2069. if (_popoverCellAjaxXhr) {
  2070. _popoverCellAjaxXhr.abort();
  2071. }
  2072. _popoverCellAjaxXhr = $.ajax({
  2073. type: 'GET',
  2074. url: priv.options.moreFunctionsCellAjaxUrl + '&ID=' + rowPK,
  2075. dataType: 'json',
  2076. contentType: "application/json; charset=utf-8",
  2077. data: ''
  2078. })
  2079. .done(function(data, textStatus, jqXHR){
  2080. if (data && 'success' === data.type) {
  2081. var popoverCellContent,
  2082. rowFunctions = [],
  2083. funcNodesToUpdate = []
  2084. ;
  2085. if (data.rowFunctions && data.rowFunctions.length > 0) {
  2086. rowFunctions = data.rowFunctions;
  2087. }
  2088. if (rowFunctions.length > 0) {
  2089. var popoverCellContent = $('<ul class="list-unstyled"></ul>');
  2090. rowFunctions.forEach(function(funObj) {
  2091. var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: true});
  2092. if (funObj.id) {
  2093. funcNodesToUpdate.push({id: funObj.id, node: funcNode});
  2094. } else {
  2095. var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
  2096. funcItemNode.append(funcNode);
  2097. }
  2098. });
  2099. } else {
  2100. popoverCellContent = '<p class="text-muted">Brak dodatkowych funkcji</p>';
  2101. }
  2102. //_popoverCell.append(popoverCellContent);// cache
  2103. if (_popoverCellCurrent) {
  2104. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  2105. if (popoverNodeId) {
  2106. var popoverNode = jQuery('#' + popoverNodeId),
  2107. popoverCntNode = popoverNode.find('.popoverCellContent'),
  2108. popoverRowFuncNode = popoverNode.find('.popoverRowFunctions');
  2109. ;
  2110. {// fix generated row Functions by loaded from ajax call
  2111. if(dbg) console.log('popoverRowFunctions. popoverRowFuncNode', popoverRowFuncNode);
  2112. if(dbg) console.log('popoverRowFunctions. funcNodesToUpdate', funcNodesToUpdate);
  2113. funcNodesToUpdate.forEach(function(funcNodeInfo) {
  2114. var className = 'func_name-' + funcNodeInfo.id,
  2115. foundRowFuncNode = null
  2116. ;
  2117. if(dbg) console.log('popoverRowFunctions. funcNodesToUpdate loop:', funcNodeInfo);
  2118. popoverRowFuncNode.find('li > a').each(function(ind, n) {
  2119. var n$ = $(n);
  2120. if(dbg) console.log('popoverRowFunctions loop(',ind,'):', n, 'data(func_name)', n$.data('func_name'), 'data', n$.data());
  2121. if (n$.hasClass(className)) {
  2122. foundRowFuncNode = n$;
  2123. }
  2124. });
  2125. if (foundRowFuncNode) {
  2126. foundRowFuncNode.replaceWith(funcNodeInfo.node);
  2127. } else {
  2128. var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
  2129. funcItemNode.append(foundRowFuncNode);
  2130. }
  2131. });
  2132. }
  2133. popoverCntNode.empty().append(popoverCellContent);
  2134. if (rowFunctions.length <= 0) {
  2135. popoverCntNode.find('p.text-muted').delay(600).hide(300);
  2136. }
  2137. }
  2138. }
  2139. }
  2140. });
  2141. };
  2142. priv.renderRowEmptyNode = function() {
  2143. var rowNode = $('<tr></tr>');
  2144. if (priv.options.rowFunctions || priv.options.filtersClean) {
  2145. $('<td class="text-right stickyCol stickyCol1">&nbsp;</td>').appendTo(rowNode);
  2146. }
  2147. if (_state.primaryKey && priv.options.checkboxes) {
  2148. var cellNode = $('<td class="stickyCol stickyCol2" style="padding:3px 5px"></td>').appendTo(rowNode);
  2149. // ReactDOM.render(
  2150. // h(P5UI__TableAjaxRowCheckbox, {
  2151. // disabled: true,
  2152. // primaryKey: 'empty',
  2153. // store: priv.options.selectedStore,
  2154. // actions: priv.options.selectedActions
  2155. // }),
  2156. // cellNode.get(0)
  2157. // );
  2158. }
  2159. for (var i = 0; i < _state.colsSorted.length; i++) {
  2160. var columnName = _state.colsSorted[i],
  2161. columnProps = _data.cols[columnName]
  2162. ;
  2163. if (!columnProps) return;
  2164. if (columnProps.hidden) continue;// "unique" is hidden - TODO: rm "unique" from _state.colsSorted ?
  2165. if (i == 1) {// TODO: 1 is pk - use better check
  2166. $('<td class="stickyCol3">&nbsp;</td>').appendTo(rowNode);
  2167. } else {
  2168. $('<td>&nbsp;</td>').appendTo(rowNode);
  2169. }
  2170. }
  2171. return rowNode;
  2172. };
  2173. priv.renderTableTheadSort = function() {
  2174. var nodeClass = 'tblAjax__' + 'head__sort'
  2175. var currentNode = _uiNode$Table.find('thead').find('.' + nodeClass)
  2176. var node = $('<tr class="sort ' + nodeClass + '"></tr>')
  2177. if (priv.options.tblFunctions || priv.options.filtersClean) {
  2178. var headCell = $('<th class="text-right head-info stickyCol stickyCol1"></th>').appendTo(node)
  2179. $.map(priv.options.tblFunctions, function (funObj, funName) {
  2180. var funHtml = $('<a></a>')
  2181. funHtml.attr('href', funObj.href || '#')
  2182. if (funObj.title) funHtml.attr('title', funObj.title)
  2183. if (funObj.icon) funHtml.html('<span class="glyphicon glyphicon-' + funObj.icon + '"></span> ')
  2184. if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
  2185. funHtml.on('click', priv[funObj.method])
  2186. }
  2187. funHtml.appendTo(headCell)
  2188. })
  2189. }
  2190. if (_state.primaryKey && priv.options.checkboxes) {
  2191. var headCell = $('<th class="stickyCol stickyCol2" style="padding:3px 5px"></th>').appendTo(node);
  2192. ReactDOM.render(
  2193. h(P5UI__TableAjaxRowCheckbox, {
  2194. namespace: priv.options.namespace,
  2195. primaryKey: 'select-all',
  2196. store: priv.options.selectedStore,
  2197. actions: priv.options.selectedActions
  2198. }),
  2199. headCell.get(0)
  2200. );
  2201. }
  2202. for (var i = 0; i < _state.colsSorted.length; i++) {
  2203. var column = _state.colsSorted[i]
  2204. var props = _data.cols[column]
  2205. if (props.hidden) continue
  2206. var headCell = $('<th class="ta-ordering"></th>').appendTo(node)
  2207. if (i == 1) headCell.addClass('stickyCol stickyCol3')
  2208. // DBG && console.log('DBG: render header cell action order by', { column, props }); // TODO: DBG isSrotable
  2209. if (props.type != 'special' && props.type != 'geom' && props.type != "simpleLink" && props.type != "ref") { // TODO: props.isSortable
  2210. headCell.on('click', {column: column}, priv.columnClicked)
  2211. }
  2212. var nodeLabel = (props.friendly) ? props.friendly : column
  2213. var nodeTitle = column
  2214. if (props.description && props.description.length > 0) {
  2215. nodeTitle = p5Utils__format("{0} ({1})", [props.description, column])
  2216. }
  2217. else if (props._tsRetId > 0) {
  2218. nodeTitle = p5Utils__format("Kliknij na pole i przejdź do powiązanych rekordów ({0})", [nodeTitle])
  2219. }
  2220. if ('ref' === props.type && props.xsdRefType) {
  2221. nodeLabel = '<i class="glyphicon glyphicon-export"></i> ' + props.xsdRefType
  2222. if (props.description && props.description.length > 0 && props.description !== column) {
  2223. nodeTitle = p5Utils__format("{0} (ref {1})", [props.description, column])
  2224. } else {
  2225. nodeTitle = p5Utils__format("(ref {0})", [column])
  2226. }
  2227. }
  2228. var headCnt = $(p5Utils__format('<span class="pull-left" title="{1}">{0}</span>', [nodeLabel, nodeTitle]))
  2229. headCnt.appendTo(headCell)
  2230. if (column == _state._currSortCol) {
  2231. headCell.addClass((_state._currSortFlip) ? 'ta-ordering-down' : 'ta-ordering-up')
  2232. }
  2233. if (column !== _state.primaryKey) {
  2234. var hideColBtn = $('<i class="glyphicon glyphicon-remove remove-cell"></i>')
  2235. hideColBtn.on('click', {column: column}, priv.columnHideClicked)
  2236. hideColBtn.appendTo(headCell)
  2237. }
  2238. }
  2239. currentNode.replaceWith(node)
  2240. };
  2241. priv.renderHeadSpecialFilters = function() {
  2242. DBG && console.warn('DBG:priv.renderHeadSpecialFilters...', { 'priv.options.specialFilterFunctions': priv.options.specialFilterFunctions });
  2243. if (!priv.options.specialFilterFunctions) {
  2244. return;
  2245. }
  2246. ReactDOM.render(
  2247. h(P5UI__TableAjaxSpecialFilters, {
  2248. store: priv.options.filterStore,
  2249. actions: priv.options.filterActions,
  2250. specialFilters: priv.options.specialFilterFunctions,
  2251. namespace: priv.options.namespace,
  2252. }),
  2253. _uiNodeSpecialFilters
  2254. );
  2255. };
  2256. priv.renderTableTheadFilter = function() {
  2257. var nodeClass = 'tblAjax__' + 'head__filter',
  2258. currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
  2259. node;
  2260. // currentNode.find('i').tooltip('hide');
  2261. node = $('<tr class="filter ' + nodeClass + '"></tr>');
  2262. //_head.find(".filter").remove();
  2263. //_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
  2264. var headCell;
  2265. var elem;
  2266. var placeHolder = '';
  2267. var tooltip = '';
  2268. //create the functions column
  2269. if (priv.options.rowFunctions || priv.options.filtersClean) {
  2270. var headCell = $('<th class="text-right stickyCol stickyCol1"></th>').appendTo(node);
  2271. headCell.css({padding: '0'});
  2272. if (priv.options.filtersClean) {
  2273. ReactDOM.render(
  2274. h(p5UI__TableAjaxClearAllFilters, {
  2275. store: priv.options.filterStore,
  2276. actions: priv.options.filterActions
  2277. }),
  2278. headCell.get(0)
  2279. );
  2280. }
  2281. }
  2282. //create the filter checkbox
  2283. if (_state.primaryKey && priv.options.checkboxes) {
  2284. // tooltip = priv.options.types.bool.filterTooltip || 'Pokaż tylko:<br/>nieokreślony,<br/>zaznaczony,<br/>niezaznaczony';
  2285. headCell = $('<th class="stickyCol stickyCol2" style="padding:0"></th>').appendTo(node);
  2286. ReactDOM.render(
  2287. h(P5UI__TableAjaxFieldCheckboxSearch, {
  2288. namespace: priv.options.namespace,
  2289. fieldName: ( priv.options.checkboxIdContext ? '@sel_' + priv.options.checkboxIdContext : '@selected' ),
  2290. store: priv.options.filterStore,
  2291. actions: priv.options.filterActions
  2292. }),
  2293. headCell.get(0)
  2294. );
  2295. }
  2296. //create the column filters
  2297. for (var i = 0; i < _state.colsSorted.length; i++) {
  2298. var column = _state.colsSorted[i];
  2299. var props = _data.cols[column];
  2300. tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
  2301. placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
  2302. if (props.hidden) continue;
  2303. headCell = $('<th></th>').appendTo(node);
  2304. headCell.css({padding: '0'});
  2305. if (i == 1) headCell.addClass('stickyCol stickyCol3');
  2306. ReactDOM.render(
  2307. h(p5UI__FieldInputFilterSearch, {
  2308. disabled: (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]),
  2309. fieldName: column,
  2310. type: props.type,
  2311. lagacyProps: props, // TODO: use ony required like xsdType
  2312. // xsdType: props.xsdType,
  2313. store: priv.options.filterStore,
  2314. onChange: function (fieldName, value) {
  2315. priv.options.filterStore.dispatch( priv.options.filterActions.delayFilter(fieldName, value) );
  2316. }
  2317. }),
  2318. headCell.get(0)
  2319. );
  2320. }
  2321. currentNode.replaceWith(node);
  2322. };
  2323. priv.renderTableTfoot = function() {
  2324. _uiNode$Table.find('tfoot').remove();
  2325. _foot = $('<tfoot></tfoot>').insertAfter(_bodyNode);
  2326. //$(_uiNodeCont).next('.foot').replaceWith(_foot);
  2327. };
  2328. priv.renderFooter = function() {
  2329. priv.renderFooterInfo();
  2330. priv.renderFooterPagination();
  2331. priv.renderFooterPageSizes();
  2332. priv.renderFooterColumnPicker();
  2333. priv.renderFooterFunctions();
  2334. priv.renderFooterExport();
  2335. };
  2336. priv.renderFooterInfo = function() {
  2337. var nodeClass = 'tblAjax__' + 'footer__toolbar__info',
  2338. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  2339. node;
  2340. if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
  2341. node = $('<div class="foot-info ' + nodeClass + '"></div>');
  2342. var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
  2343. var total = _data.total;
  2344. var toRow = Math.min(fromRow + _state.pageSize, total);
  2345. if (_data.total > 0) {
  2346. $(p5Utils__format('<p>Wiersze od {0} do {1} z {2}</p>', [fromRow + 1, toRow, total])).appendTo(node);
  2347. } else {
  2348. $('<p>Brak wierszy pasujących do kryteriów wyszukiwania</p>').appendTo(node);
  2349. }
  2350. currentNode.replaceWith(node);
  2351. };
  2352. priv.renderFooterPagination = function() {
  2353. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
  2354. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  2355. node;
  2356. var currPage = _state.page;
  2357. var totalPages = Math.ceil(_data.total / _state.pageSize);
  2358. if (priv.options.debug || DBG) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
  2359. if (_data.total > 0) {
  2360. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  2361. var lowerPage = currPage - 2;
  2362. var upperPage = currPage + 2;
  2363. if (upperPage > totalPages) {
  2364. var diff = upperPage - totalPages;
  2365. upperPage = totalPages;
  2366. lowerPage -= diff;
  2367. }
  2368. if (lowerPage < 1) lowerPage = 1;
  2369. if (upperPage < 5) upperPage = 5;
  2370. //$(p5Utils__format('<li class="{0}"><a href="#">&lt;&lt;</a></li>', [currPage == 1 ? 'disabled' : '']))
  2371. $(p5Utils__format('<button type="button" class="btn btn-default{0}">&lt;&lt;</button>', [currPage == 1 ? ' disabled' : '']))
  2372. .on('click', {pageIndex: 1}, priv.pageChanged)
  2373. .appendTo(node);
  2374. //$(p5Utils__format('<li class="{0}"><a href="#">&lt;</a></li>', [currPage == 1 ? 'disabled' : '']))
  2375. $(p5Utils__format('<button type="button" class="btn btn-default{0}">&lt;</button>', [currPage == 1 ? ' disabled' : '']))
  2376. .on('click', {pageIndex: currPage - 1}, priv.pageChanged)
  2377. .appendTo(node);
  2378. for (var i = lowerPage; i <= upperPage; i++) {
  2379. var link;
  2380. //if (i != currPage) link = $(p5Utils__format('<li class="{1}"><a href="#">{0}</a></li>', [i, i > totalPages ? 'disabled' : '']));
  2381. if (i != currPage) link = $(p5Utils__format('<button type="button" class="btn btn-default{1}">{0}</button>', [i, i > totalPages ? ' disabled' : '']));
  2382. //if (i == currPage) link = $(p5Utils__format('<li class="active"><a href="#">{0}</a></li>', [i]));
  2383. if (i == currPage) link = $(p5Utils__format('<button type="button" class="btn btn-default active">{0}</button>', [i]));
  2384. if (link) {
  2385. link.on('click', {pageIndex: i}, priv.pageChanged);
  2386. link.appendTo(node);
  2387. }
  2388. }
  2389. //$(p5Utils__format('<li class="{0}"><a href="#">&gt;</a></li>', [currPage == totalPages ? 'disabled' : '']))
  2390. $(p5Utils__format('<button type="button" class="btn btn-default{0}">&gt;</button>', [currPage == totalPages ? ' disabled' : '']))
  2391. .on('click', {pageIndex: currPage + 1}, priv.pageChanged)
  2392. .appendTo(node);
  2393. //$(p5Utils__format('<li class="{0}"><a href="#">&gt;&gt;</a></li>', [currPage == totalPages ? 'disabled' : '']))
  2394. $(p5Utils__format('<button type="button" class="btn btn-default{0}">&gt;&gt;</button>', [currPage == totalPages ? ' disabled' : '']))
  2395. .on('click', {pageIndex: totalPages}, priv.pageChanged)
  2396. .appendTo(node);
  2397. } else {
  2398. node = $('<span class="' + nodeClass + '"></span>');
  2399. }
  2400. currentNode.replaceWith(node);
  2401. };
  2402. priv.renderFooterPageSizes = function() {
  2403. var nodeClass = 'tblAjax__' + 'footer__toolbar__pagesizes',
  2404. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  2405. node;
  2406. if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
  2407. if (_data.total > 0 && priv.options.pageSizes.length > 0) {
  2408. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  2409. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy&nbsp;</button>').appendTo(node);
  2410. var span = $('<span class="caret"></span>').appendTo(btn);
  2411. var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
  2412. $.each(priv.options.pageSizes, function(index, val) {
  2413. var li = $('<li></li>').appendTo(ul);
  2414. if (val == priv.options.pageSize) {
  2415. $(p5Utils__format('<a style="color:#337AB7;">{0}</a>', [val])).appendTo(li);
  2416. } else {
  2417. $(p5Utils__format('<a href="#">{0}</a>', [val])).appendTo(li);
  2418. }
  2419. });
  2420. node.on('click', 'a', priv.pageSizeChanged);
  2421. } else {
  2422. node = $('<span class="' + nodeClass + '"></span>');
  2423. }
  2424. currentNode.replaceWith(node);
  2425. };
  2426. priv.renderFooterColumnPicker = function() {
  2427. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  2428. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  2429. node;
  2430. if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
  2431. if (priv.options.columnPicker) {
  2432. node = $('<div class="btn-group dropup columnpicker ' + nodeClass + '"></div>');
  2433. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Kolumny&nbsp;</button>').appendTo(node);
  2434. var span = $('<span class="caret"></span>').appendTo(btn);
  2435. var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
  2436. var selectedFilter = priv.modelColFilter_getSelected();
  2437. priv.modelColFilter_getFilters().map(function(colFltr) {
  2438. var li = $('<li></li>').appendTo(ul),
  2439. selected = (selectedFilter && selectedFilter == colFltr.name)? 'checked="checked"' : '',
  2440. input = '<input ' + selected + ' type="radio" style="margin:0"/>',
  2441. a = $('<a href="#" data-col_filter="' + colFltr.name + '" style="padding:0px 20px;">' + input + ' ' + colFltr.label + '</a>').appendTo(li);
  2442. if ('all' != colFltr.name && 'most_used' != colFltr.name) {
  2443. arm = $('<button data-col_filter="' + colFltr.name + '" class="pull-right btn btn-xs btn-link" style="margin:0;padding:0;border:0;color:red">' + '&times;' + '</a>').appendTo(a);
  2444. arm.on('click', priv.modelColFilter_onClickRemoveFilter)
  2445. }
  2446. });
  2447. {// if (!selectedFilter) {// save current filter
  2448. var li = $('<li style="text-align:center; clear:both"></li>').appendTo(ul)
  2449. priv.modelColFilter_getSaveBtn().appendTo(li);
  2450. }
  2451. $('<li class="divider"></li>').appendTo(ul);
  2452. $.each(_data.cols, function(col, props) {
  2453. if (props.type != "unique" && col != _state.primaryKey) {
  2454. var li = $('<li></li>').appendTo(ul),
  2455. label = (props.friendly || col).replace(/<br\/?>/g, ' '),
  2456. input = p5Utils__format('<input {0} type="checkbox" title="{1}" value="{1}" style="margin:0"/>&nbsp;{2}', [(props.hidden) ? '' : 'checked', col, label]),
  2457. a = $('<a href="#" style="padding:0px 20px;">' + input + '</a>').appendTo(li);
  2458. }
  2459. });
  2460. node.on('click', 'input[type="checkbox"]', priv.columnPickerClicked);
  2461. node.on('click', 'a', priv.columnPickerLinkClicked);
  2462. } else {
  2463. node = $('<span class="' + nodeClass + '"></span>');
  2464. }
  2465. currentNode.replaceWith(node);
  2466. };
  2467. priv.renderFooterFunctions = function() {
  2468. var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
  2469. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  2470. node;
  2471. if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
  2472. if (priv.options.tblFunctions) {
  2473. node = $('<div class="btn-group ' + nodeClass + '"></div>');
  2474. $.map(priv.options.tblFunctions, function(funObj, funName){
  2475. var funHtml = $('<button class="btn btn-sm btn-default"></button>');
  2476. if (funObj.title) funHtml.attr('title', funObj.title);
  2477. if (funObj.method) funHtml.on('click', priv[funObj.method]);
  2478. else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
  2479. var funIconHtml = $('<i></i>');
  2480. if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
  2481. funIconHtml.prependTo(funHtml);
  2482. funHtml.addClass('btn');
  2483. funHtml.appendTo(node);
  2484. });
  2485. } else {
  2486. node = $('<span class="' + nodeClass + '"></span>');
  2487. }
  2488. currentNode.replaceWith(node);
  2489. };
  2490. priv.renderFooterExport = function() {
  2491. var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
  2492. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
  2493. node;
  2494. if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
  2495. if (priv.options.exportFields && priv.options.exportFields.length) {
  2496. node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
  2497. var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export&nbsp;</button>').appendTo(node);
  2498. var span = $('<span class="caret"></span>').appendTo(btn);
  2499. var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
  2500. $.each(_data.cols, function(col, props) {
  2501. if (-1 !== priv.options.exportFields.indexOf(col)) {
  2502. var li = $('<li></li>').appendTo(ul);
  2503. $(p5Utils__format('<input {0} type="checkbox" title="{1}" value="{1}" >&nbsp;{2}</input>', [(_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col])).appendTo(li);
  2504. li.on('click', 'input', priv.exportFieldChanged);
  2505. }
  2506. });
  2507. var li = $('<li></li>').appendTo(ul);
  2508. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
  2509. li.on('click', 'a', priv.exportToHTML);
  2510. var li = $('<li></li>').appendTo(ul);
  2511. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
  2512. li.on('click', 'a', priv.exportToCSV);
  2513. var li = $('<li></li>').appendTo(ul);
  2514. $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export do pliku CSV w kodowaniu Windows-1250"></i>Export do CSV (Windows-1250)</a>').appendTo(li);
  2515. li.on('click', 'a', priv.exportToCSVWinCP1250);
  2516. } else {
  2517. node = $('<span class="' + nodeClass + '"></span>');
  2518. }
  2519. currentNode.replaceWith(node);
  2520. };
  2521. priv.renderInlineEditBox = function() {
  2522. var nodeClass = 'tblAjax__' + 'inlineEditBox',
  2523. currentNode = $(_uiNodeCont).parent().children('.' + nodeClass),
  2524. node;
  2525. var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
  2526. var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
  2527. var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
  2528. var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
  2529. var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
  2530. $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
  2531. $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
  2532. var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
  2533. var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
  2534. $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
  2535. $('<input type="hidden" name="col" value="">').appendTo(iebBody);
  2536. $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
  2537. var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
  2538. $('<button class="btn btn-close" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
  2539. var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
  2540. frmInlineEdit.on('submit', function() {
  2541. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  2542. var data = inlineEditBox$Node.find('form').serialize();
  2543. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  2544. function notifyAjaxCallback(data) {
  2545. var notify = {};
  2546. notify.type = (data && data.type)? data.type : '';
  2547. notify.msg = (data && data.msg)? data.msg : '';
  2548. switch (notify.type) {
  2549. case 'success':
  2550. if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
  2551. break;
  2552. case 'info':
  2553. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  2554. break;
  2555. case 'error':
  2556. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2557. break;
  2558. case 'warning':
  2559. notify.type = 'warn';
  2560. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2561. break;
  2562. default:
  2563. notify.msg = 'Nieznany błąd';
  2564. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2565. notify.type = '';
  2566. }
  2567. jQuery.notify(notify.msg, notify.type);
  2568. }
  2569. $.ajax({
  2570. data: data,
  2571. dataType: 'json',
  2572. type: "POST",
  2573. url: priv.options.editInlineSaveUrl
  2574. })
  2575. .done(function(data, textStatus, jqXHR){
  2576. notifyAjaxCallback(data);
  2577. publ.refresh();
  2578. inlineEditBox$Node.modal('hide');
  2579. })
  2580. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2581. if (jqXHR.responseJSON) {
  2582. notifyAjaxCallback(jqXHR.responseJSON);
  2583. }
  2584. else {
  2585. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2586. if (jqXHR.status == 404) {
  2587. jQuery.notify(jqXHR.responseText, 'error');
  2588. } else {
  2589. jQuery.notify(jqXHR.responseText, 'warn');
  2590. }
  2591. }
  2592. inlineEditBox$Node.modal('hide');
  2593. });
  2594. return false;
  2595. });
  2596. currentNode.replaceWith(node);
  2597. };
  2598. priv.exportFieldChanged = function(e) {
  2599. e.stopPropagation();
  2600. var column = $(this).val();
  2601. _exportFieldsSelect[column] = !_exportFieldsSelect[column];
  2602. };
  2603. priv.exportToHTML = function(e) {
  2604. priv.exportData('html', $(this), e);
  2605. };
  2606. priv.exportToCSV = function(e) {
  2607. priv.exportData('csv', $(this), e);
  2608. };
  2609. priv.exportToCSVWinCP1250 = function(e) {
  2610. priv.exportData('csv_cp1250', $(this), e);
  2611. };
  2612. priv.exportData = function(format, node, e) {
  2613. var exportFields = [];
  2614. $.each(_exportFieldsSelect, function(col, selected) {
  2615. if (selected) {
  2616. exportFields.push(col);
  2617. }
  2618. });
  2619. if (!exportFields.length) {
  2620. alert('Nie wybrano żadnych pól do eksportu.');
  2621. e.preventDefault();
  2622. return false;
  2623. }
  2624. var limit = 10000;
  2625. if (!_data.total || _data.total <= 0) {
  2626. alert('Brak rekordów do eksportu.');
  2627. e.preventDefault();
  2628. return false;
  2629. }
  2630. if (_data.total > limit) {
  2631. if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
  2632. e.preventDefault();
  2633. return false;
  2634. }
  2635. }
  2636. var exportUrl = 'index.php?_route=ViewTableAjax&_task=export&namespace=' + priv.options.namespace;
  2637. exportUrl += '&format=' + format;
  2638. exportUrl += '&flds=' + exportFields.join(',');
  2639. exportUrl += '&sortCol=' + (_state._currSortCol || '');
  2640. exportUrl += '&sortDir=' + (_state._currSortFlip ? "desc" : "asc");
  2641. exportUrl += (_state._filterQuery) ? "&" + _state._filterQuery : "";
  2642. exportUrl += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
  2643. exportUrl += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
  2644. node.attr('href', exportUrl);
  2645. };
  2646. priv.showFailFetchDataMsg = function () {
  2647. var clearAllFiltersBtn = jQuery('<button class="btn btn-xs btn-link" style="color:red">usunąć wszystkie filtry</button>')
  2648. clearAllFiltersBtn.on('click', function () {
  2649. priv.options.filterStore.dispatch( priv.options.filterActions.clearAllFilters() )
  2650. jQuery(this).parent().remove();
  2651. })
  2652. var msgNode = jQuery('<div class="alert alert-danger" style="clear:both; max-width:600px; margin: 10px auto">' +
  2653. 'Wystąpił błąd podczas pobierania danych ' +
  2654. '<a href="javascript:window.location.reload()" class="btn btn-xs btn-link">spróbuj ponownie</a>.' + '<br>' +
  2655. 'Jeśli problem się powtarza, spróbuj ' +
  2656. '</div>')
  2657. msgNode.append(clearAllFiltersBtn);
  2658. jQuery(_uiNodeCont).prepend(msgNode);
  2659. }
  2660. /*
  2661. calls the webservice(if defined).
  2662. used only inside priv.init
  2663. */
  2664. priv.update = function(callback) {
  2665. var skipCols, resetChecked;// undefined
  2666. if (!priv.options.url) {
  2667. if (priv.options.debug || DBG) console.log('no url found');
  2668. return;
  2669. }
  2670. if (priv.options.debug || DBG) console.log(p5Utils__format('requesting data from url:{0}', [priv.options.url]));
  2671. var initUrlAdd = '';
  2672. initUrlAdd += '&currSortCol=' + _state._currSortCol;
  2673. initUrlAdd += '&currSortFlip=' + ( _state._currSortCol ? "desc" : "asc" );
  2674. DBG && console.warn('DBG:update... - FETCH_DATA', { '_state._filterQuery': _state._filterQuery, '_state._specialFilterQuery': _state._specialFilterQuery, _state });
  2675. initUrlAdd += (_state._filterQuery) ? "&" + _state._filterQuery : "";
  2676. initUrlAdd += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
  2677. initUrlAdd += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
  2678. // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych (init) ...'});
  2679. window.fetch(priv.options.url + initUrlAdd, {
  2680. method: priv.options.urlPost ? 'POST' : 'GET',
  2681. credentials: 'same-origin',// add cookies
  2682. }).then(function (response) {
  2683. return response.json()
  2684. }).then(function (data) {
  2685. if (priv.options.debug || DBG) console.log('loadDataAjax:fetch:update: request finished response data:', data);
  2686. if ('success' == data.type) {
  2687. return data;
  2688. } else {
  2689. p5UI__notifyAjaxCallback(data);
  2690. priv.showFailFetchDataMsg();
  2691. }
  2692. return null;
  2693. }).then(function (data) {
  2694. if (priv.options.debug || DBG) console.log('loadDataAjax:fetch:update: request finished data:', data);
  2695. if (!data) return;
  2696. if (data && data.cols) {
  2697. priv.setStateCols(data.cols, data.primaryKey);
  2698. }
  2699. // assign the new state (data)
  2700. state = {data: {}};
  2701. if (!skipCols) state.data.cols = data.cols || {};
  2702. state.data.rows = data.rows || [];
  2703. state.data.total = data.total || 0;
  2704. state.data.primaryKey = data.primaryKey || 'ID';
  2705. state.page = data.page || 0;
  2706. state.pageSize = data.pageSize || priv.options.pageSize;
  2707. state.filters = data.filters || {};
  2708. priv.setState(state);
  2709. if (typeof callback == "function") {
  2710. callback.call(this);
  2711. }
  2712. }).catch(function (e) {
  2713. console.log('loadDataAjax:fetch: ERR:', e);
  2714. });
  2715. };
  2716. /*
  2717. assigns the new data.
  2718. */
  2719. priv.setState = function(state) {
  2720. var oldState = _state; // TODO: use to check what really changed (use extend!)
  2721. var renderParts = {};
  2722. if (state.data) {
  2723. if (state.data.cols && Object.keys(state.data.cols).length > 0) {// TODO: never happen, but if happend then rerender all
  2724. priv.setStateCols(state.data.cols, state.data.primaryKey);
  2725. priv.setStateData(state.data);
  2726. } else {
  2727. priv.setStateData(state.data);
  2728. }
  2729. renderParts['body'] = true;
  2730. renderParts['foot_pagination'] = true;
  2731. }
  2732. if (state.hasOwnProperty('specialFilters')) {
  2733. _state.specialFilters = state.specialFilters;
  2734. renderParts['head__specialFilters'] = true;
  2735. }
  2736. if (state.hasOwnProperty('page')) {
  2737. if (state.page != _state.page) {
  2738. _state.page = state.page;
  2739. renderParts['foot_pagination'] = true;
  2740. }
  2741. }
  2742. if (state.hasOwnProperty('pageSize')) {
  2743. if (state.pageSize != _state.pageSize) {
  2744. _state.pageSize = state.pageSize;
  2745. renderParts['foot_pagination'] = true;
  2746. }
  2747. }
  2748. if (state.hasOwnProperty('filters')) {
  2749. renderParts['head__specialFilters'] = true;
  2750. renderParts['foot_pagination'] = true;
  2751. }
  2752. renderParts = Object.keys(renderParts);
  2753. if (priv.options.debug || DBG) console.log('setState::renderParts: ', renderParts);//TODO:DBG:RMME
  2754. if (renderParts.length > 0) {
  2755. jQuery(_uiNodeCont).trigger('TableAjax:render', renderParts);
  2756. }
  2757. };
  2758. priv.setStateCols = function(cols, primaryKey) {
  2759. if (priv.options.debug || DBG) console.log('priv.setStateCols: ', {primaryKey: primaryKey, cols: cols});
  2760. // console.log("priv.setStateCols");
  2761. // console.trace();
  2762. _state.cols = cols;
  2763. _state.primaryKey = primaryKey || _state.primaryKey;
  2764. // fix col name - props.column
  2765. $.each(_state.cols, function(col, props) {
  2766. props.column = col;
  2767. });
  2768. // fix col types - default 'string'
  2769. $.each(_state.cols, function(col, props) {
  2770. if (!props.type) cols[col].type = "string";
  2771. });
  2772. // fix props.filter - set true if not set - TODO: allow filter this col?
  2773. $.each(_state.cols, function(col, props) {
  2774. if (props.filter == undefined) props.filter = true;
  2775. });
  2776. if (_state.primaryKey) {
  2777. //create a unique column definition
  2778. _state.cols["unique"] = {
  2779. column: "unique",
  2780. type: "unique",
  2781. index: -1,
  2782. hidden: true
  2783. };
  2784. }
  2785. _state.colsSorted = Object.keys(_state.cols).sort(function(a, b) {
  2786. return _state.cols[a].index - _state.cols[b].index;
  2787. });
  2788. };
  2789. priv.setStateData = function(pData) {
  2790. var listPrimaryKeys = (pData && pData.rows && pData.rows.length)
  2791. ? pData.rows.map(function (item) {
  2792. return item['@primaryKey'];
  2793. })
  2794. : []
  2795. ;
  2796. jQuery(_uiNodeCont).trigger('TableAjax:updateRows', { primaryKeys: listPrimaryKeys });
  2797. if (priv.options.checkboxes) {
  2798. priv.options.selectedStore.dispatch( priv.options.selectedActions.setPrimaryKeys(priv.options.namespace, listPrimaryKeys) );
  2799. }
  2800. var data = $.extend(true, {}, pData);
  2801. data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
  2802. _data = data;
  2803. _data.rowsOrg = _data.rows;
  2804. //we might have more/less data now. Recalculate stuff.
  2805. if (_state.page > 1) {
  2806. _totalPages = Math.ceil(_data.total / priv.options.pageSize);
  2807. }
  2808. };
  2809. /*
  2810. helper that returns the underlying data by the unique value
  2811. */
  2812. priv.getRow = function(uniqueValue) {
  2813. var row;
  2814. $.each(_data.rowsOrg, function(i, r) {
  2815. if (r[_state.primaryKey] == uniqueValue) {
  2816. row = r;
  2817. return false;
  2818. }
  2819. });
  2820. return row;
  2821. };
  2822. priv.longTextChanged = function(e) {
  2823. priv.options.longDesc = !priv.options.longDesc;
  2824. _bodyNode.find('td').each(function(ind, el){
  2825. var $el = jQuery(el);
  2826. if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
  2827. if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
  2828. if (priv.options.longDesc) {
  2829. $el.addClass('tbl-short-txt');
  2830. var $elSpan = jQuery(el.firstChild);
  2831. $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
  2832. } else {
  2833. $el.removeClass('tbl-short-txt');
  2834. }
  2835. }
  2836. }
  2837. });
  2838. return false;
  2839. };
  2840. priv.mapEditorHide = function() {
  2841. priv.options.mapEditor = false;
  2842. if ('window' == priv.options.mapEditorContainer) {
  2843. //_mapEditorDialog.dialog("close");
  2844. _mapEditorDialog.dialog("destroy");
  2845. }
  2846. _mapEditorWrap.hide();
  2847. _mapEditor.hide();
  2848. };
  2849. priv.mapEditorShow = function() {
  2850. //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
  2851. priv.options.mapEditor = true;
  2852. _mapEditor.show();
  2853. _mapEditorWrap.show();
  2854. _mapEditor.TableAjaxMap({
  2855. //debug: true,
  2856. wpsUrl: 'http://biuro.biall-net.pl/wps',
  2857. wfsUrl: 'http://biuro.biall-net.pl/wps',
  2858. showAddLayerWidget: (priv.options.hasAdditionalLayers) ? true : false,
  2859. zoomStrategyActivate: 14,
  2860. layerName: priv.options.labelHtml,
  2861. addBtn: {
  2862. title: 'Przenieś mapę do okna',
  2863. displayClass: 'mapEditor-btnBackToWindow',
  2864. trigger: function() {
  2865. priv.mapEditorHide();
  2866. priv.options.mapEditorContainer = 'window';
  2867. priv.mapEditorShow();
  2868. priv.resizableMapDockNode('destroy');
  2869. }
  2870. },
  2871. onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
  2872. if (priv.options.debug || DBG) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
  2873. if (!selectedRecordId) {
  2874. alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
  2875. return;
  2876. }
  2877. function notifyAjaxCallback(data) {
  2878. var notify = {};
  2879. notify.type = (data && data.type)? data.type : '';
  2880. notify.msg = (data && data.msg)? data.msg : '';
  2881. switch (notify.type) {
  2882. case 'success':
  2883. if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
  2884. break;
  2885. case 'info':
  2886. if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
  2887. break;
  2888. case 'error':
  2889. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2890. break;
  2891. case 'warning':
  2892. notify.type = 'warn';
  2893. if (!notify.msg) notify.msg = 'Wystąpiły błędy';
  2894. break;
  2895. default:
  2896. notify.msg = 'Nieznany błąd';
  2897. if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
  2898. notify.type = '';
  2899. }
  2900. jQuery.notify(notify.msg, notify.type);
  2901. }
  2902. $.ajax({
  2903. data: {polygon: selectedFeatureExtent},
  2904. dataType: 'json',
  2905. type: "POST",
  2906. url: priv.options.theGeomSaveUrl + '&ID=' + selectedRecordId
  2907. })
  2908. .done(function(data, textStatus, jqXHR){
  2909. notifyAjaxCallback(data);
  2910. //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
  2911. publ.loadPage(0);// TODO: reload table data
  2912. })
  2913. .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
  2914. if (jqXHR.responseJSON) {
  2915. notifyAjaxCallback(jqXHR.responseJSON);
  2916. }
  2917. else {
  2918. var txt = jqXHR.responseText || 'Wystąpiły błędy';
  2919. if (jqXHR.status == 404) {
  2920. jQuery.notify(jqXHR.responseText, 'error');
  2921. } else {
  2922. jQuery.notify(jqXHR.responseText, 'warn');
  2923. }
  2924. }
  2925. });
  2926. },
  2927. onSelectBox: function(bounds) {
  2928. if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
  2929. var column = 'the_geom';
  2930. var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
  2931. priv.options.filterStore.dispatch( priv.options.filterActions.setFilter(column, filter) )
  2932. }
  2933. }
  2934. });
  2935. priv.mapEditorShowElement();
  2936. };
  2937. priv.mapEditorShowElement = function() {
  2938. if ('window' == priv.options.mapEditorContainer) {
  2939. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2940. if (!mapEditor || !mapEditor.length) {
  2941. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  2942. var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
  2943. if (!mapEditor || !mapEditor.length) {
  2944. // TODO: create new map
  2945. }
  2946. _mapEditorWrap.append(mapEditor);
  2947. }
  2948. _mapEditorWrap.css({padding:'5px'});
  2949. _mapEditorDialog = _mapEditorWrap.dialog({
  2950. width: 540,
  2951. minWidth: 400,
  2952. minHeight: 400,
  2953. open: function(e, ui) {
  2954. var n = jQuery(this),
  2955. mapWrap = n.children(":first"),
  2956. map = mapWrap.children(":first");
  2957. map.css({width: n.width() - 5, height: n.height() - 5});
  2958. _mapEditor.TableAjaxMapUpdateSize();
  2959. },
  2960. resizeStart: function(e, ui) {
  2961. jQuery(this).children(":first").children(":first").css({display:'none'});
  2962. },
  2963. resizeStop: function(e, ui){
  2964. var n = jQuery(this),
  2965. map = n.children(":first").children(":first");
  2966. n.css({width: n.parent().width()});
  2967. map.css({display: 'block', height: n.height(), width: n.width()});
  2968. _mapEditor.TableAjaxMapUpdateSize();
  2969. },
  2970. dragStop: function(e, ui){
  2971. _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
  2972. }
  2973. });
  2974. _mapEditorWrap.bind('dialogclose', function(e) {
  2975. priv.options.mapEditor = false;
  2976. });
  2977. var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
  2978. var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
  2979. if (dialogTitleBarCloseBtn) {
  2980. var btnToggle = jQuery('<span style="width:18px;height:18px;position:absolute;top:50%;right:25px;margin-top:-9px;" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-icon-only"><i style="margin-top:3px;" class="glyphicon glyphicon-fullscreen"></i></span>');
  2981. btnToggle.on('click', function(e) {
  2982. priv.options.mapEditorContainer = 'dock';
  2983. _mapEditorWrap.dialog('close');
  2984. priv.mapEditorShowElement();
  2985. });
  2986. btnToggle.insertBefore(dialogTitleBarCloseBtn);
  2987. }
  2988. }
  2989. else if ('dock' == priv.options.mapEditorContainer) {
  2990. priv.resizableMapDockNode('prepare');
  2991. _mapEditor.TableAjaxMapUpdateSize();
  2992. }
  2993. };
  2994. priv.resizableMapDockNode = function(task) {
  2995. if ('prepare' == task) {
  2996. var mapEditor = _mapEditorWrap.children('.mapEditor-map');
  2997. if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
  2998. var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
  2999. var tblCont = jQuery(_uiNodeCont).parent('.AjaxTableCont');
  3000. tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
  3001. var breadcrumb = tblCont.children('.breadcrumb');
  3002. if (!breadcrumb || !breadcrumb.length) {
  3003. tblCont.prepend(mapDockNode);
  3004. } else {
  3005. mapDockNode.insertAfter(breadcrumb);
  3006. }
  3007. mapDockNode.append(mapEditor);
  3008. }
  3009. var mapDockResizable = mapEditor.parent();
  3010. mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
  3011. var resizeLineHeigth = 6;
  3012. mapDockResizable.children(":first").css({height: 'auto'});
  3013. mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
  3014. mapEditor.css({marginBottom: resizeLineHeigth+'px'});
  3015. mapEditor.children(":first").css({width: mapEditor.width()});
  3016. mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
  3017. mapDockResizable.on('resizestart', function(event, ui) {
  3018. ui.element.children(":first").children(":first").css({display:'none'})
  3019. });
  3020. mapDockResizable.on('resizestop', function(event, ui) {
  3021. ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
  3022. });
  3023. } else if ('destroy' == task) {
  3024. var mapDockResizable = jQuery(_uiNodeCont).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
  3025. mapDockResizable.resizable('destroy');
  3026. mapDockResizable.remove();
  3027. }
  3028. };
  3029. priv.mapEditorChanged = function(e) {
  3030. if (priv.options.debug || DBG) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
  3031. priv.options.mapEditor = !priv.options.mapEditor;
  3032. if (priv.options.mapEditor) {
  3033. priv.mapEditorShow();
  3034. }
  3035. else {
  3036. priv.mapEditorHide();
  3037. }
  3038. return false;
  3039. };
  3040. /*
  3041. when: changing page in pager
  3042. what: triggers table to be created with new page
  3043. */
  3044. priv.pageChanged = function(e) {
  3045. e.preventDefault();
  3046. var totalPages = Math.ceil(_data.total / _state.pageSize);
  3047. if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
  3048. //set the new page
  3049. _state.page = e.data.pageIndex;
  3050. publ.loadPage(_state.page);
  3051. };
  3052. /*
  3053. when: changing pagesize in pagesize dropdown
  3054. what: triggers table to be created with new pagesize
  3055. */
  3056. priv.pageSizeChanged = function(e) {
  3057. e.preventDefault();
  3058. var val = $(this).text();
  3059. if (priv.options.debug || DBG) console.log(p5Utils__format('pagesize changed to:{0}', [val]));
  3060. if (parseInt(val) == priv.options.pageSize) {
  3061. return false;
  3062. }
  3063. priv.options.pageSize = parseInt(val);
  3064. publ.loadPage(1, priv.options.pageSize);
  3065. jQuery(_uiNodeCont).trigger('TableAjax:render', ['body', 'foot_pagination']);
  3066. priv.saveProfilePageSize(priv.options.pageSize);
  3067. };
  3068. /*
  3069. when: clicking a column
  3070. what: triggers table to be sorted by the column
  3071. */
  3072. priv.columnClicked = function(e) {
  3073. e.preventDefault();
  3074. if (priv.options.debug || DBG) console.log(p5Utils__format('col:{0} clicked', [e.data.column]));
  3075. priv.options.filterStore.dispatch( priv.options.filterActions.toggleSort(e.data.column) )
  3076. };
  3077. priv.saveProfilePageSize = function(pageSize) {
  3078. var reqData = {};
  3079. reqData.pageSize = pageSize;
  3080. $.ajax({
  3081. data: reqData,
  3082. type: "POST",
  3083. dataType: 'json',
  3084. // async: true,
  3085. url: priv.options.pageSizeSave
  3086. })
  3087. .done(function(data, textStatus, jqXHR){
  3088. if (data && data.type && data.type == 'info') {
  3089. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  3090. } else {
  3091. jQuery.notify('Zapisano ustawienia', 'success');
  3092. }
  3093. })
  3094. .fail(function(){
  3095. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  3096. });
  3097. };
  3098. priv.saveHiddenCols = function() {
  3099. var reqData = {};
  3100. $.each(_data.cols, function(col, props) {
  3101. if (props.type != "unique" && col != 'unique' && col != _state.primaryKey) {
  3102. reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
  3103. }
  3104. });
  3105. $.ajax({
  3106. data: reqData,
  3107. type: "POST",
  3108. dataType: 'json',
  3109. // async: true,
  3110. url: priv.options.hiddenColsSaveUrl
  3111. })
  3112. .done(function(data, textStatus, jqXHR){
  3113. if (data && data.type && data.type == 'info') {
  3114. jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
  3115. } else {
  3116. jQuery.notify('Zapisano ustawienia', 'success');
  3117. }
  3118. })
  3119. .fail(function(){
  3120. jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
  3121. });
  3122. };
  3123. /*
  3124. when: clicking a column in columnpicker
  3125. what: triggers table to show/hide the column
  3126. */
  3127. priv.columnPickerClicked = function(e) {
  3128. e.stopPropagation();
  3129. var column = $(this).val();
  3130. //toggle column visibility
  3131. priv.modelColFilter_toggleColumn(column);
  3132. priv.saveHiddenCols();
  3133. //_data.cols[column].index = new priv.ext.XDate();
  3134. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  3135. };
  3136. priv.modelColFilter_init = function() {// run only once, set _state._modelColFilter {selected, filters: [ {name, label, visibleCols} ]}
  3137. var isAllSelected = true;
  3138. if (undefined === _state._modelColFilter) {
  3139. var columnFilters = [];
  3140. {
  3141. var fltrAll = {'name': 'all', 'label': 'Wszystkie', visibleCols: []};
  3142. $.each(_data.cols, function(col, props) {
  3143. if ("unique" == props.type) return;
  3144. fltrAll.visibleCols.push(col);
  3145. if (_data.cols[col].hidden) isAllSelected = false;
  3146. });
  3147. columnFilters.push(fltrAll);
  3148. }
  3149. // {
  3150. // var fltrMostUsed = {'name': 'most_used', 'label': 'Najczęściej używane', visibleCols: []};
  3151. // var fltrMostUsedLimit = 10;
  3152. // $.each(_data.cols, function(col, props) {
  3153. // if ("unique" == props.type) return;
  3154. // if (fltrMostUsedLimit-- > 0) {
  3155. // fltrMostUsed.visibleCols.push(col);
  3156. // }
  3157. // });
  3158. // columnFilters.push(fltrMostUsed);
  3159. // }
  3160. _state._modelColFilter = {
  3161. selected: (isAllSelected)? 'all' : null,
  3162. filters: columnFilters,
  3163. saveBtn: $('<button class="btn btn-xs btn-primary" disabled="disabled">Zapisz widoczne kolumny</button>')
  3164. };
  3165. _state._modelColFilter.saveBtn.on('click', priv.modelColFilter_saveBtnClicked)
  3166. if (priv.options.userTableFilterUrl) {
  3167. window.fetch(priv.options.userTableFilterUrl, {
  3168. method: 'POST',
  3169. headers: {
  3170. 'Content-Type': 'application/json'
  3171. },
  3172. credentials: 'same-origin',// add cookies
  3173. body: JSON.stringify({
  3174. namespace: priv.options.namespace,
  3175. })
  3176. }).then(function (response) {
  3177. return response.json()
  3178. }).then(function (result) {
  3179. if ('success' == result.type) {
  3180. // p5UI__notifyAjaxCallback(result)
  3181. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  3182. return ('all' === filter.name || 'most_used' == filter.name)
  3183. }).concat(Object.keys(result.data).map(function (fltr) {
  3184. return {
  3185. name: fltr,
  3186. label: fltr,
  3187. visibleCols: result.data[fltr].split(',')
  3188. }
  3189. }))
  3190. jQuery(_uiNodeCont).trigger('TableAjax:render', ['foot__columnPicker']);
  3191. } else {
  3192. p5UI__notifyAjaxCallback(result)
  3193. }
  3194. }).catch(function (e) {
  3195. // TODO: show error ("ajax response error: " + e)
  3196. });
  3197. }
  3198. }
  3199. };
  3200. priv.modelColFilter_onClickRemoveFilter = function (e) {
  3201. e.preventDefault()
  3202. e.stopPropagation()
  3203. var filtrName = $(this).data('col_filter')
  3204. if (!filtrName) return
  3205. window.fetch(priv.options.rmUserTableFilterAjaxUrl, {
  3206. method: 'POST',
  3207. headers: {
  3208. 'Content-Type': 'application/json'
  3209. },
  3210. credentials: 'same-origin',// add cookies
  3211. body: JSON.stringify({
  3212. namespace: priv.options.namespace,
  3213. filtrName: filtrName,
  3214. })
  3215. }).then(function (response) {
  3216. return response.json()
  3217. }).then(function (result) {
  3218. if ('success' == result.type) {
  3219. p5UI__notifyAjaxCallback(result)
  3220. var userTableFilters = result.data;// resolve(result.data)
  3221. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  3222. return ('all' === filter.name || 'most_used' == filter.name)
  3223. }).concat(Object.keys(userTableFilters).map(function (fltr) {
  3224. return {
  3225. name: fltr,
  3226. label: fltr,
  3227. visibleCols: userTableFilters[fltr].split(',')
  3228. }
  3229. }))
  3230. jQuery(_uiNodeCont).trigger('TableAjax:render', ['foot__columnPicker']);
  3231. } else {
  3232. p5UI__notifyAjaxCallback(result)
  3233. }
  3234. }).catch(function (e) {
  3235. p5UI__notifyAjaxCallback({ type: 'error', msg: new String(e) })
  3236. });
  3237. };
  3238. priv.modelColFilter_saveBtnClicked = function (e) {
  3239. swal({
  3240. title: 'Zapisz widoczne kolumny',
  3241. html: '',
  3242. animation: true,
  3243. input: 'text',
  3244. inputPlaceholder: 'nazwa filtra',
  3245. // inputValue: null,
  3246. // inputAttributes: {'step': '0.01'},
  3247. showCancelButton: true,
  3248. confirmButtonText: 'Zapisz',
  3249. showLoaderOnConfirm: true,
  3250. showCloseButton: true,
  3251. preConfirm: function(filtrName) {
  3252. return new Promise(function(resolve, reject) {
  3253. if (!filtrName) reject('Proszę podać nazwę filtra')
  3254. if (filtrName.length > 255) reject('Nazwa za długa')
  3255. window.fetch(priv.options.addUserTableFilterAjaxUrl, {
  3256. method: 'POST',
  3257. headers: {
  3258. 'Content-Type': 'application/json'
  3259. },
  3260. credentials: 'same-origin',// add cookies
  3261. body: JSON.stringify({
  3262. namespace: priv.options.namespace,
  3263. filtrName: filtrName,
  3264. visibleCols: Object.keys(_data.cols).filter(function(col) {
  3265. return !_data.cols[col].hidden
  3266. }).join(','),
  3267. })
  3268. }).then(function (response) {
  3269. return response.text()
  3270. }).then(function (responseText) {
  3271. try {
  3272. // json = response.json() // BUG: error trafia do catch promisów, zamiast aktualnego bloku
  3273. // -- obiekt response pewnie jest powiązany z Promisem z fetch
  3274. // -- response.json() zwraca Promise tak samo jak response.text()
  3275. return JSON.parse(responseText)
  3276. } catch (e) {
  3277. throw responseText
  3278. }
  3279. }).then(function (result) {
  3280. if ('success' == result.type) {
  3281. p5UI__notifyAjaxCallback(result)
  3282. resolve(result.data)
  3283. } else {
  3284. p5UI__notifyAjaxCallback(result)
  3285. reject(result.msg || "Wystąpił błąd!")
  3286. }
  3287. }).catch(function (e) {
  3288. reject("ajax response error: " + e)
  3289. });
  3290. })
  3291. },
  3292. allowOutsideClick: false
  3293. }).then(function(userTableFilters) {
  3294. _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
  3295. return ('all' === filter.name || 'most_used' == filter.name)
  3296. }).concat(Object.keys(userTableFilters).map(function (fltr) {
  3297. return {
  3298. name: fltr,
  3299. label: fltr,
  3300. visibleCols: userTableFilters[fltr].split(',')
  3301. }
  3302. }))
  3303. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  3304. }).catch(function(e) {
  3305. // eg. hit Cancel
  3306. })
  3307. }
  3308. priv.modelColFilter_getSaveBtn = function () {
  3309. priv.modelColFilter_init();
  3310. return _state._modelColFilter.saveBtn
  3311. }
  3312. priv.modelColFilter_getFilters = function() {
  3313. priv.modelColFilter_init();
  3314. return _state._modelColFilter.filters;
  3315. };
  3316. priv.modelColFilter_getSelected = function() {
  3317. priv.modelColFilter_init();
  3318. return _state._modelColFilter.selected;
  3319. };
  3320. priv.modelColFilter_setFilter = function(filterKey) {
  3321. priv.modelColFilter_init();
  3322. _state._modelColFilter.selected = filterKey;
  3323. priv.modelColFilter_uiUncheckAllColFilters();
  3324. priv.modelColFilter_uiCheckColFilter(filterKey);
  3325. };
  3326. priv.modelColFilter_toggleColumn = function(column, value) {
  3327. priv.modelColFilter_init();
  3328. _state._modelColFilter.selected = null;
  3329. if (!_data.cols[column] || !_data.cols[column]) return;
  3330. _data.cols[column].hidden = (undefined !== value)? value : !_data.cols[column].hidden;
  3331. priv.modelColFilter_uiUncheckAllColFilters();
  3332. {
  3333. var isAllSelected = true;
  3334. $.each(_data.cols, function(col, props) {
  3335. if ("unique" == props.type) return;
  3336. if (_data.cols[col].hidden) isAllSelected = false;
  3337. });
  3338. if (isAllSelected) {
  3339. _state._modelColFilter.selected = 'all';
  3340. priv.modelColFilter_uiCheckColFilter('all');
  3341. }
  3342. }
  3343. };
  3344. priv.modelColFilter_uiUncheckAllColFilters = function() {
  3345. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  3346. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  3347. ;
  3348. currentNode.find('input[type="radio"]').prop("checked", false);
  3349. };
  3350. priv.modelColFilter_uiCheckColFilter = function(filterKey) {
  3351. var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
  3352. currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
  3353. ;
  3354. currentNode.find('input[type="radio"]').each(function(idx, input) {
  3355. var input$ = jQuery(input);
  3356. if (filterKey == jQuery(input$).parent().data('col_filter')) {
  3357. input$.prop("checked", true);
  3358. } else {
  3359. input$.prop("checked", false);
  3360. }
  3361. });
  3362. };
  3363. priv.columnPickerLinkClicked = function(e) {
  3364. e.stopPropagation();
  3365. var input$ = $(this).find('input'),
  3366. col_filter = $(this).data('col_filter'),
  3367. columnFilters = priv.modelColFilter_getFilters()
  3368. ;
  3369. if (col_filter) {
  3370. var filter = null;
  3371. $.each(columnFilters, function(idx, colFltr) {
  3372. if (col_filter == colFltr.name) {
  3373. filter = colFltr;
  3374. }
  3375. });
  3376. if (!filter) return;
  3377. $.each(_data.cols, function(col, props) {
  3378. var isHidden = (-1 === filter.visibleCols.indexOf(col));
  3379. priv.modelColFilter_toggleColumn(col, isHidden);
  3380. });
  3381. priv.modelColFilter_setFilter(col_filter);
  3382. priv.saveHiddenCols();
  3383. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  3384. } else {
  3385. e.preventDefault();
  3386. if (input$.length != 1) return;
  3387. var column = input$.val();
  3388. if (!column) return;
  3389. //toggle column visibility
  3390. priv.modelColFilter_toggleColumn(column);
  3391. input$.prop("checked", !input$.is(':checked'));// update view
  3392. priv.saveHiddenCols();
  3393. //_data.cols[column].index = new priv.ext.XDate();
  3394. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body']);
  3395. }
  3396. };
  3397. priv.columnHideClicked = function(e) {
  3398. e.stopPropagation();
  3399. var column;
  3400. if (e.data && e.data.column) {
  3401. column = e.data.column;
  3402. } else {
  3403. return;
  3404. }
  3405. //toggle column visibility
  3406. priv.modelColFilter_toggleColumn(column);
  3407. priv.saveHiddenCols();
  3408. //_data.cols[column].index = new priv.ext.XDate();
  3409. jQuery(_uiNodeCont).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
  3410. };
  3411. /*
  3412. when: clicking anywhere on a row
  3413. what: row data and other info is returned to caller
  3414. */
  3415. // priv.rowClicked = function(e) {// TODO: not used
  3416. // if (!_state.primaryKey) {
  3417. // if (priv.options.debug || DBG) console.log('no unique column specified');
  3418. // return;
  3419. // }
  3420. //
  3421. // //gather callback data
  3422. // var elem = $(this);
  3423. // var column = _data.cols[elem.data('column')];
  3424. // var unique = elem.closest('tr').data('unique');
  3425. // var row = priv.getRow(unique);
  3426. // var isChecked = elem.closest('tr').find('.unique').is(':checked');
  3427. //
  3428. // //trigger callback
  3429. // if (typeof priv.options.rowClicked == 'function') {
  3430. // priv.options.rowClicked.call(e.target, {
  3431. // event: e,
  3432. // row: row,
  3433. // column: column,
  3434. // checked: isChecked
  3435. // });
  3436. // }
  3437. // };
  3438. /**
  3439. * Inline edit.
  3440. */
  3441. priv.rowDblClicked = function(e) {
  3442. var inlineEditBox$Node = $(_uiNodeCont).parent().children('.tblAjax__inlineEditBox');
  3443. // hide popover for typespecial fld on click
  3444. if (_popoverCellCurrent) {
  3445. _popoverCellCurrent.popover('hide');
  3446. }
  3447. // e.clientX: 1002; e.clientY: 245
  3448. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  3449. inlineEditBox$Node.modal();
  3450. inlineEditBox$Node.show();
  3451. inlineEditBox$Node.on('shown.bs.modal', function(e) {
  3452. var dialogBox = jQuery(this).find('.modal-dialog'),
  3453. modalBody = dialogBox.find('.modal-body'),
  3454. boudingRect = dialogBox.get(0).getBoundingClientRect();
  3455. dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
  3456. modalBody.css({overflow: 'scroll'});
  3457. dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
  3458. dialogBox.draggable({handle: '.modal-header'});
  3459. });
  3460. inlineEditBox$Node.on('hidden.bs.modal', function(e) {
  3461. var dialogBox = jQuery(this).find('.modal-dialog'),
  3462. modalBody = dialogBox.find('.modal-body');
  3463. dialogBox.removeAttr('style');
  3464. modalBody.removeAttr('style');
  3465. modalBody.css({padding: '0'});
  3466. dialogBox.resizable();
  3467. dialogBox.draggable();
  3468. dialogBox.resizable('destroy');
  3469. dialogBox.draggable('destroy');
  3470. });
  3471. inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
  3472. inlineEditBox$Node.find('input[name=col]').val(e.data.col);
  3473. inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
  3474. $.ajax({
  3475. url: priv.options.editInlineUrl + '&ID=' + e.data.id + '&col=' + e.data.col,
  3476. type: 'GET',
  3477. dataType: 'json',
  3478. success: function(data) {
  3479. if ('p5:www_link' == _.get(data, 'simpleType')) {
  3480. inlineEditBox$Node.find('.inlineEditBox-cnt').empty();
  3481. var label = jQuery('<label>');// for="' + data.htmlFieldName + '">');// "<label for="f22579" class="AjaxTableEdit-label"> ... </label>
  3482. label.attr('for', data.htmlFieldName);
  3483. label.attr('class', 'AjaxTableEdit-label');
  3484. inlineEditBox$Node.find('.inlineEditBox-cnt').append(label);
  3485. var inLabel = jQuery('<strong title="[' + data.idZasob + '] ' + data.fieldLabel + '">' + data.fieldLabel + '</strong>');
  3486. label.append(inLabel);
  3487. var frmItem = jQuery('<input>');
  3488. frmItem.attr('type', 'text');
  3489. frmItem.attr('name', data.htmlFieldName);
  3490. frmItem.attr('value', data.formItem.value);
  3491. frmItem.attr('maxlength', _.get(data, 'restrictions.maxLength', 255));
  3492. frmItem.attr('style', 'width:98%');
  3493. frmItem.attr('class', 'form-control');
  3494. frmItem.insertAfter(label);
  3495. } else {
  3496. var content = _.get(data, 'legacy_html', "Nieznany błąd");
  3497. inlineEditBox$Node.find('.inlineEditBox-cnt').html(content);
  3498. }
  3499. inlineEditBox$Node.find('.btn-save').show();
  3500. initDateTimePicker(inlineEditBox$Node);
  3501. inlineEditBox$Node.find('textarea').autosize();
  3502. var fld = inlineEditBox$Node.find('input[name^="f"]');
  3503. if (fld.length > 0 && !fld.hasClass('se_type-date')) {
  3504. fld.keydown(function(event) {
  3505. if (event.which == 13) {
  3506. event.preventDefault();
  3507. inlineEditBox$Node.find('form').submit();
  3508. }
  3509. });
  3510. }
  3511. (function setFocusAtFirstInlineEditFormFld(modal$node){
  3512. var fld, dbg = false;
  3513. if(dbg)console.log('focus...');
  3514. fld = modal$node.find('input[name^="f"]:first');
  3515. if (fld.length > 0 && !fld.hasClass('se_type-date')) {
  3516. if(dbg)console.log('set focus to first input element');
  3517. fld.focus(); return;
  3518. }
  3519. fld = modal$node.find('select[name^="f"]:first');
  3520. if (fld.length) {
  3521. if (fld.get(0).selectize) {
  3522. if(dbg)console.log('set focus to first typepecial element');
  3523. } else {
  3524. if(dbg)console.log('set focus to first select element');
  3525. fld.focus(); return;
  3526. }
  3527. }
  3528. if(dbg)console.log('set focus to close btn');
  3529. modal$node.find('.btn-close').focus();
  3530. })(inlineEditBox$Node);
  3531. },
  3532. error: function(err) {
  3533. if (priv.options.debug || DBG) console.log('err');
  3534. }
  3535. });
  3536. } else {
  3537. if (priv.options.debug || DBG) console.log('NO data');
  3538. return false;
  3539. }
  3540. };
  3541. priv.ajaxLoadTypeSpeciallCell = function(id, col) {
  3542. if (_popoverCellAjaxXhr) {
  3543. _popoverCellAjaxXhr.abort();
  3544. }
  3545. _popoverCellAjaxXhr = $.ajax({
  3546. type: 'GET',
  3547. url: 'index.php?_route=ViewTableAjax&_task=typeSpecialCell&namespace=' + priv.options.namespace + '&ID=' + id + '&col=' + col,
  3548. dataType: 'json',
  3549. contentType: "application/json; charset=utf-8",
  3550. data: '',
  3551. success: function(req){
  3552. if (_.get(req, 'data.tbl_id') > 0) {
  3553. var addHtml = '';
  3554. for (var i in req.data.items) {
  3555. var url = 'index.php?_route=ViewTableAjax';
  3556. url += '&namespace=' + req.namespace;
  3557. url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
  3558. url += '&_hash=' + Math.random().toString(36).substring(2);
  3559. addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
  3560. addHtml += '<br>';
  3561. }
  3562. //_popoverCell.append(addHtml);// cache
  3563. if (_popoverCellCurrent) {
  3564. var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
  3565. if (popoverNodeId) {
  3566. jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
  3567. }
  3568. }
  3569. }
  3570. }
  3571. });
  3572. };
  3573. priv.popoverCellTypeSpecial = function(e) {
  3574. e.preventDefault();
  3575. e.stopPropagation();
  3576. if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
  3577. var lastId = _popoverCell.data('rowid'),
  3578. lastCol = _popoverCell.data('col'),
  3579. rowPK = e.data.id,
  3580. colName = e.data.col
  3581. ;
  3582. if (lastId == rowPK && lastCol == colName) {
  3583. //_popoverCellCurrent.popover('toggle');
  3584. }
  3585. else {
  3586. if (_popoverCellCurrent) {
  3587. _popoverCellCurrent.popover('destroy');
  3588. }
  3589. _popoverCell.data('rowid', rowPK);
  3590. _popoverCell.data('col', colName);
  3591. _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
  3592. _popoverCellCurrent = jQuery(e.currentTarget);
  3593. // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">&times;</button>'
  3594. var opts = {
  3595. placement: 'left'
  3596. , trigger: 'click'
  3597. // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
  3598. , title: '<div style="display:block;position:relative;padding:0 20px 0 0;">' + (e.data.friendly || colName) + ' <button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:0;top:0;">&times;</button>' + '</div>'
  3599. , html: true
  3600. , content: _popoverCell.html()
  3601. }
  3602. _popoverCellCurrent.popover(opts);
  3603. if (_data.cols[colName]) {
  3604. if (_data.cols[colName]._tsRetId > 0) {
  3605. _popoverCellCurrent.on('shown.bs.popover', function() {
  3606. priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
  3607. });
  3608. }
  3609. }
  3610. _popoverCellCurrent.popover('show');
  3611. }
  3612. } else {
  3613. if (priv.options.debug || DBG) console.log('NO data');
  3614. return false;
  3615. }
  3616. return;
  3617. };
  3618. priv.routeChanged = function(e) {
  3619. hash = e.data.hash || '';
  3620. if (hash.length == 0) {
  3621. return;
  3622. }
  3623. if (hash.substring(0, 1) != '#') {
  3624. hash = '#' + hash;
  3625. }
  3626. location.hash = hash;
  3627. };
  3628. priv.refresh = function(e) {
  3629. e.preventDefault();
  3630. publ.loadPage(_state.page);
  3631. };
  3632. publ.init = function(options) {
  3633. if (priv.options.debug || DBG) console.log('TableAjax initialization...');
  3634. //merge supplied options with defaults
  3635. $.extend(priv.options, defaults, options);
  3636. priv.init();
  3637. return publ;
  3638. };
  3639. publ.refresh = function() {
  3640. publ.loadPage(_state.page);
  3641. };
  3642. publ.loadPage = function(page, pageSize) {
  3643. priv.loadPage(page, pageSize);
  3644. }
  3645. priv.loadPage = function(page, pageSize) {
  3646. var resetChecked = false;
  3647. var reqData = {
  3648. page: page,
  3649. pageSize: (pageSize || priv.options.pageSize),
  3650. currSortCol: (_state._currSortCol || ''),
  3651. currSortFlip: _state._currSortFlip ? "desc" : "asc"
  3652. };
  3653. var urlAdd = '';
  3654. urlAdd += '&page=' + page;
  3655. urlAdd += '&pageSize=' + (pageSize || priv.options.pageSize);
  3656. urlAdd += '&currSortCol=' + (_state._currSortCol || '');
  3657. urlAdd += '&currSortFlip=' + (_state._currSortFlip ? "desc" : "asc");
  3658. // TODO: compare with filterStore
  3659. DBG && console.warn('DBG:loadPage... FETCH_DATA', { '_state._filterQuery': _state._filterQuery, '_state._specialFilterQuery': _state._specialFilterQuery, _state });
  3660. urlAdd += (_state._filterQuery) ? "&" + _state._filterQuery : "";
  3661. urlAdd += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
  3662. urlAdd += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
  3663. _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
  3664. // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych...'});
  3665. window.fetch(priv.options.url + urlAdd, {
  3666. method: priv.options.urlPost ? 'POST' : 'GET',
  3667. credentials: 'same-origin',// add cookies
  3668. }).then(function (response) {
  3669. return response.json()
  3670. }).then(function (data) {
  3671. if (priv.options.debug || DBG) console.log('loadDataAjax:fetch:loadPage: request finished, data:', data);
  3672. // p5UI__notifyAjaxCallback(data);
  3673. if ('success' == data.type) {
  3674. state = {data: {}};
  3675. state.data.cols = data.cols || {};
  3676. state.data.rows = data.rows || [];
  3677. state.data.total = data.total || 0;
  3678. state.data.primaryKey = data.primaryKey || 'ID';
  3679. state.page = data.page || 0;
  3680. state.pageSize = data.pageSize || priv.options.pageSize;
  3681. state.filters = data.filters || {};
  3682. priv.setState(state);
  3683. _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
  3684. } else {
  3685. p5UI__notifyAjaxCallback(data);
  3686. priv.showFailFetchDataMsg();
  3687. }
  3688. }).catch(function (e) {
  3689. console.log('loadDataAjax:fetch: ERR:', e);
  3690. });
  3691. };
  3692. publ.getCurrentPage = function() {
  3693. return _state.page;
  3694. };
  3695. publ.popoverCellRemove = function() {
  3696. if (_popoverCellCurrent) {
  3697. _popoverCellCurrent.popover('destroy');
  3698. }
  3699. _popoverCell.data('rowid', -1);
  3700. _popoverCell.data('col', -1);
  3701. _popoverCell.html('');
  3702. };
  3703. return publ;
  3704. }
  3705. $.fn.TableAjax = function(options) {
  3706. options = options || {};
  3707. return this.each(function() {
  3708. options.id = this;
  3709. $(this).data('TableAjax', new TableAjax().init(options));
  3710. });
  3711. };
  3712. $.fn.TableAjaxLoadPage = function(page, pageSize) {
  3713. return this.each(function() {
  3714. var tblAjax = jQuery(this).data('TableAjax');
  3715. var curPage = page || tblAjax.getCurrentPage();
  3716. if (tblAjax) tblAjax.loadPage(curPage, pageSize);
  3717. });
  3718. };
  3719. $.fn.TableAjaxRefresh = function(page, pageSize) {
  3720. return this.each(function() {
  3721. var tblAjax = jQuery(this).data('TableAjax');
  3722. if (tblAjax) tblAjax.refresh();
  3723. });
  3724. };