TableAjax.php.TableAjax.js 149 KB

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