TableAjax.php.TableAjax.js 149 KB

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