TableAjax.php.TableAjax.js 145 KB

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