TableAjax.php.TableAjax.js 134 KB

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