TableAjax.php.TableAjax.js 137 KB

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