TableAjax.php.TableAjax.js 150 KB

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