TableAjax.php.TableAjax.js 150 KB

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