TableAjax.php.TableAjax.js 146 KB

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