TableAjax.php.TableAjax.js 147 KB

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