TableAjax.php.TableAjax.js 149 KB

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