TableAjax.php.TableAjax.js 145 KB

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