TableAjax.php.TableAjax.js 149 KB

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