TableAjax.php.TableAjax.js 149 KB

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