TableAjax.php.TableAjax.js 139 KB

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