| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898 |
- if (!URI_BASE) throw "Missing URI_BASE"; // => Request::getPathUri()
- if (!URI_WPS) throw "Missing URI_WPS";
- if (!global.jQuery) throw "Missing jQuery"
- var $ = global.jQuery
- var RENDER_AS_REACT = Boolean(RENDER_AS_REACT) || false
- var SKIP_TOTAL = Boolean(SKIP_TOTAL) || false
- var DBG = DBG || false;
- var DBG1 = true;
- if (!global.p5VendorJs) throw "Missing p5 Vendor js libs";
- if (!global.p5VendorJs.Redux) throw "Missing p5 Vendor js lib: Redux";
- if (!global.createTableFiltersStateObject) throw "Missing createTableFiltersStateObject";
- if (!global.createTableSelectedStateObject) throw "Missing createTableSelectedStateObject";
- if (!global.createTableDataStateObject) throw "Missing createTableDataStateObject";
- var createReactClass = global.p5VendorJs.createReactClass;
- var h = global.p5VendorJs.React.createElement;
- var React = global.p5VendorJs.React;
- var ReactDOM = global.p5VendorJs.ReactDOM;
- var Redux = global.p5VendorJs.Redux;
- var ReduxThunk = global.p5VendorJs.ReduxThunk;
- var createStoreWithThunkMiddleware = Redux.applyMiddleware(ReduxThunk)(Redux.createStore); // TODO: to vendor.js
- var p5UI__FieldCheckboxSearch = global.p5VendorJs['p5UI__FieldCheckboxSearch'];
- var p5UI__FieldCheckboxLoading = global.p5VendorJs['p5UI__FieldCheckboxLoading'];
- var p5UI__TableAjaxWidget = global.p5VendorJs['p5UI__TableAjax'];
- var P5UI__TableAjaxSortableLabel = global.p5VendorJs['P5UI__TableAjaxSortableLabel'];
- var P5UI__TableAjaxRowCheckbox = global.p5VendorJs['P5UI__TableAjaxRowCheckbox'];
- var P5UI__TableAjaxSelectedInfo = global.p5VendorJs['P5UI__TableAjaxSelectedInfo'];
- if (!String.prototype.startsWith) { // TODO: to global js utils
- String.prototype.startsWith = function(search, pos) {
- return this.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
- };
- }
- var p5WfsRefFilter = (function () { // convert GET param key ogc filter for ref
- return {
- parse: function (filterKey) {
- if (filterKey.startsWith('Ref_From_')) return { type: 'From', idInstance: filterKey.substr('Ref_From_'.length) };
- if (filterKey.startsWith('Ref_To_')) return { type: 'To', idInstance: filterKey.substr('Ref_To_'.length) };
- return null;
- }
- };
- })();
- function p5Utils__mapToQuery(map, callback) {
- var mapCallback = ('function' === typeof callback) ? callback : function (key) {
- return '' + key + '=' + encodeURIComponent(map.get(key));
- };
- return Array.from(map.keys()).sort()
- .map(mapCallback)
- .join('&')
- }
- function p5Utils__mapToQueryWithKeyPrefix(map, keyPrefix, callback) {
- var mapCallback = ('function' === typeof callback) ? callback : function (key) {
- return '' + (keyPrefix || '') + key + '=' + encodeURIComponent(map.get(key));
- };
- return p5Utils__mapToQuery(map, mapCallback)
- }
- function p5Utils__objectToQueryWithKeyPrefix(obj, prefix, callback) {
- if (!obj) return '';
- var mapCallback = ('function' === typeof callback) ? callback : function (key) {
- return '' + key + '=' + encodeURIComponent(obj[key]);
- };
- return Object.keys(obj).sort()
- .map(mapCallback)
- .join('&')
- }
- function p5Utils__multiReplaceValues(input, row) {
- return Object.keys(row).reduce(function (ret, fieldName) {
- return ret.replace(new RegExp('\{' + fieldName + '\}', 'g'), row[fieldName])
- }, input)
- }
- global['P5UI__TableAjaxSpecialFilter'] = createReactClass({
- // props.store: Redux store with state: { isLoading bool, selected array of strings }
- // props.actions: Redux store actions
- // props.name: PropTypes.string.isRequired
- // props.values: PropTypes.array.isRequired
- // props.icon: PropTypes.string.isRequired
- // props.label: PropTypes.string
- getStateFromStore: function () {
- var state = this.props.store.getState();
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::getStateFromStore (name:'+this.props.name+')', { store: state, name: this.props.name, selected: state.specialFilter.get(this.props.name) });
- return {
- selected: state.specialFilter.get(this.props.name),
- };
- },
- getInitialState: function () {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::componentDidMount (name:'+this.props.name+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::storeUpdated (name:'+this.props.name+')');
- this.setState(this.getStateFromStore())
- },
- shouldComponentUpdate: function (nextProps, nextState) {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::shouldComponentUpdate (name:'+this.props.name+')', { state: this.state, nextState});
- return (
- this.state.selected !== nextState.selected
- );
- },
- handleRemoveFilter: function (event) {
- this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, '') );
- },
- handleSetFilter: function (value) {
- this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, value) );
- },
- renderButton: function (buttonKey) {
- var option = buttonKey;
- var props = this.props.values[option];
- var value = props.value || '';
- var state = this.props.store.getState();
- DBG && console.warn('DBG:renderButton state', { state, props, value });
- var active = (value === this.state.selected);
- return h('button', {
- className: "btn btn-xs btn-default" + ( active ? " active" : "" ),
- onClick: function (event) {
- DBG && console.warn('DBG:renderButton click', { value });
- this.handleSetFilter(value);
- }.bind(this),
- style: (this.state.selected) ? { borderTopColor: "#46b8da", borderBottomColor: "#46b8da" } : {},
- }, option);
- },
- render: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilter::render (name:'+this.props.name+')', { state: this.state, props: this.props });
- var label = this.props.label || this.props.name;
- return h('div', { className: "btn-group", style: { margin: '0 4px 0 0' } },
- [
- h('button', {
- className: "btn btn-xs btn-default",
- title: label,
- style: (this.state.selected) ? { backgroundColor: "#d9edf7", borderColor: "#46b8da" } : {},
- }, [
- h('i', { className: this.props.icon })
- ])
- ].concat(
- Object.keys(this.props.values).map(this.renderButton)
- ).concat(
- [
- h('button', {
- className: "btn btn-xs btn-default",
- title: "Kasuj filtr",
- disabled: !this.state.selected,
- onClick: this.handleRemoveFilter,
- style: Object.assign(
- { color: !this.state.selected ? '#bbb' : '#f00' },
- (this.state.selected) ? { backgroundColor: "#d9edf7", borderColor: "#46b8da" } : {}
- ),
- }, [
- h('i', { className: "glyphicon glyphicon-remove" })
- ])
- ]
- )
- );
- }
- });
- global['P5UI__TableAjaxSpecialFilterRelations'] = createReactClass({
- // props.store: Redux store with state: { isLoading bool, selected array of strings }
- // props.actions: Redux store actions
- // props.name: PropTypes.string.isRequired
- // props.values: PropTypes.array.isRequired
- // props.icon: PropTypes.string.isRequired
- // props.label: PropTypes.string
- // props.availableBackRefs: PropTypes.array.isRequired // array of objects { id, namespace, label }
- // props.availableChildRefs: PropTypes.array.isRequired // array of objects { id, namespace, label }
- getStateFromStore: function () {
- var state = this.props.store.getState();
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::getStateFromStore (name:'+this.props.name+')', { store: state, name: this.props.name, selected: state.specialFilter.get(this.props.name) });
- var selected = []; // Array of { idInstance, primaryKey }
- state.specialFilter.forEach(function (value, key) {
- var refInfo = p5WfsRefFilter.parse(key); // null | { type: 'From' | 'To', idInstance: int }
- if (refInfo) {
- selected.push(Object.assign(refInfo, { primaryKey: value, filterKey: key }))
- }
- })
- DBG && console.log('TODO: DBG::P5UI__TableAjaxSpecialFilterRelations::getStateFromStore (name:'+this.props.name+')', { store: state, name: this.props.name, selected });
- return {
- selected: selected,
- };
- },
- getInitialState: function () {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::componentDidMount (name:'+this.props.name+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::storeUpdated (name:'+this.props.name+')');
- this.setState(this.getStateFromStore())
- },
- shouldComponentUpdate: function (nextProps, nextState) {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::shouldComponentUpdate (name:'+this.props.name+')', { state: this.state, nextState});
- return (
- this.state.selected !== nextState.selected
- );
- },
- handleRemoveFilter: function (event) {
- this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, '') );
- },
- handleSetFilter: function (value) {
- this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.name, value) );
- },
- handleCreate: function () {
- // TODO: save swal reference to variable to avoid open twice?
- var inputOptions = {};
- if (this.props.availableBackRefs) this.props.availableBackRefs.forEach(function (instanceInfo) {
- inputOptions[ 'From_' + instanceInfo.id ] = "z " + instanceInfo.label || instanceInfo.namespace;
- });
- if (this.props.availableChildRefs) this.props.availableChildRefs.forEach(function (instanceInfo) {
- inputOptions[ 'To_' + instanceInfo.id ] = "do " + instanceInfo.label || instanceInfo.namespace;
- });
- swal({
- title: "Wybierz rodzaj relacji",
- input: 'select',
- inputOptions: inputOptions,
- inputPlaceholder: "Wybierz",
- showCancelButton: true,
- cancelButtonText: "Anuluj",
- animation: false,
- inputValidator: function (value) {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::inputValidator', value);
- return new Promise(function (resolve) {
- if (!value) {
- resolve('Nie wybrano obiektu');
- } else {
- resolve();
- }
- });
- },
- }).then(this.handleInstanceCreate) // args: { value: ... }
- },
- handleInstanceCreate: function (result) {
- if (!result.value) return; // cancel when result = { dismiss: "cancel" }
- var idInstance = '';
- var type = '';
- var instanceLabel = '';
- if ('From_' === result.value.substr(0, 'From_'.length)) {
- type = 'From';
- idInstance = result.value.substr('From_'.length);
- if (this.props.availableBackRefs) this.props.availableBackRefs.forEach(function (instanceInfo) {
- if (idInstance == instanceInfo.id) instanceLabel = instanceInfo.label || instanceInfo.namespace;
- });
- }
- else if ('To_' === result.value.substr(0, 'To_'.length)) {
- type = 'To';
- idInstance = result.value.substr('To_'.length);
- if (this.props.availableChildRefs) this.props.availableChildRefs.forEach(function (instanceInfo) {
- if (idInstance == instanceInfo.id) instanceLabel = instanceInfo.label || instanceInfo.namespace;
- });
- }
- 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 });
- swal({
- title: "Wybierz obiekt",
- html: (instanceLabel) ? "typu: " + instanceLabel : "",
- input: 'text',
- inputPlaceholder: "Wybierz obiekt",
- showCancelButton: true,
- cancelButtonText: "Anuluj",
- animation: false,
- inputValidator: function (value) {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::inputValidator', value);
- return new Promise(function (resolve) {
- if (!value) {
- resolve('Nie podano obiektu');
- } else {
- resolve();
- }
- });
- },
- preConfirm: function (value) {
- return {
- type: type,
- idInstance: idInstance,
- primaryKey: value,
- }
- }
- }).then(this.handleInstancePrimaryKeySelected) // args: { value: { idInstance, primaryKey } }
- },
- handleInstancePrimaryKeySelected: function (result) {
- if (!result.value) return; // cancel when result = { dismiss: "cancel" }
- var type = result.value.type;
- var idInstance = result.value.idInstance;
- var primaryKey = result.value.primaryKey;
- 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 });
- this.props.store.dispatch( this.props.actions.setSpecialFilter('Ref_' + type + '_' + idInstance, primaryKey) );
- },
- renderButton: function (buttonKey) {
- var option = buttonKey;
- var props = this.props.values[option];
- var value = props.value || '';
- var state = this.props.store.getState();
- DBG && console.warn('DBG:renderButton state', { state, props, value });
- var active = (value === this.state.selected);
- return h('button', {
- className: "btn btn-xs btn-default" + ( active ? " active" : "" ),
- onClick: function (event) {
- DBG && console.warn('DBG:renderButton click', { value });
- this.handleSetFilter(value);
- }.bind(this),
- }, option);
- },
- renderLabel: function () {
- var label = this.props.label || this.props.name;
- return h('button', {
- className: "btn btn-xs btn-default",
- title: label,
- style: {
- color: '#31708f',
- backgroundColor: '#d9edf7',
- }
- }, [
- h('i', { className: this.props.icon }),
- " Filtr relacji: ",
- ]);
- },
- renderListSelected: function () { // @return array of react nodes
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::this.props.availableBackRefs (name:'+this.props.name+')', { state: this.state, props: this.props, availableBackRefs: this.props.availableBackRefs });
- return this.state.selected.map(this.renderSelected);
- },
- renderSelected: function (selected) { // @selected: { type: 'From' | 'To', filterKey, idInstance, primaryKey }, @return react node
- var filterKey = selected.filterKey;
- var type = selected.type; // From | To - backRef | childRef
- var idInstance = selected.idInstance;
- var primaryKey = selected.primaryKey;
- var namespace = idInstance;
- var label = "" + idInstance + "." + primaryKey + "";
- if ('From' === type) {
- var foundInstanceInfo = this.props.availableBackRefs.filter(function (instanceInfo) {
- return ( parseInt(idInstance) === parseInt(instanceInfo.id) );
- });
- if (foundInstanceInfo.length > 0) label = 'z ' + foundInstanceInfo[0].label + "." + primaryKey;
- if (foundInstanceInfo.length > 0) namespace = foundInstanceInfo[0].namespace;
- } else if ('To' === type) {
- var foundInstanceInfo = this.props.availableChildRefs.filter(function (instanceInfo) {
- return ( parseInt(idInstance) === parseInt(instanceInfo.id) );
- });
- if (foundInstanceInfo.length > 0) label = 'do ' + foundInstanceInfo[0].label + "." + primaryKey;
- if (foundInstanceInfo.length > 0) namespace = foundInstanceInfo[0].namespace;
- }
- return h(P5UI__TableAjaxSpecialFilterRelationFrom, {
- filterKey: filterKey,
- label: label,
- namespace: namespace,
- primaryKey: primaryKey,
- store: this.props.store,
- actions: this.props.actions,
- });
- },
- renderBackRef: function () { // @return react node - button with dropdown to select primaryKey from parent instance + remove button if selected
- return null;
- },
- renderCreateButton: function () {
- return h('button', {
- className: "btn btn-xs btn-default",
- title: "Dodaj nowy filtr relacji",
- onClick: this.handleCreate,
- }, [
- h('i', { className: 'glyphicon glyphicon-plus' })
- ]);
- },
- render: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelations::render (name:'+this.props.name+')', { state: this.state, props: this.props });
- return h('div', { className: "btn-group", style: { margin: '0 4px 0 0' } },
- [
- this.renderLabel(),
- ].concat(
- this.renderListSelected()
- ).concat([
- this.renderCreateButton()
- ])
- // Object.keys(this.props.values).map(this.renderButton)
- // ).concat(
- // [
- // h('button', {
- // className: "btn btn-xs btn-default",
- // title: "Kasuj filtr",
- // disabled: !this.state.selected,
- // onClick: this.handleRemoveFilter,
- // style: { color: !this.state.selected ? '#bbb' : '#f00' }
- // }, [
- // h('i', { className: "glyphicon glyphicon-remove" })
- // ])
- // ]
- );
- }
- });
- global['P5UI__TableAjaxSpecialFilterRelationFrom'] = createReactClass({
- handleRemoveFilter: function (event) {
- this.props.store.dispatch( this.props.actions.setSpecialFilter(this.props.filterKey, '') );
- },
- render: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilterRelationFrom::render (filterKey:'+this.props.filterKey+')', { state: this.state, props: this.props });
- var refInfo = p5WfsRefFilter.parse(this.props.filterKey); // null | { type: 'From' | 'To', idInstance: int }
- return h('button', {
- className: "btn btn-xs btn-default active",
- title: "Powiązane" + ( 'From' === refInfo.type ? " z " : " do " ) + this.props.namespace + " " + this.props.primaryKey,
- // onClick: this.handleUpdate, // TODO: paste param
- }, [
- this.props.label,
- h('i', {
- className: 'glyphicon glyphicon-remove',
- style: {
- color: '#f00',
- opacity: 0.5,
- marginLeft: "3px",
- },
- onClick: this.handleRemoveFilter,
- })
- ]);
- }
- });
- global['P5UI__TableAjaxSpecialFilters'] = createReactClass({
- // props.store: Redux store with state: { isLoading bool, selected array of strings }
- // props.actions: Redux store actions
- // props.namespace: PropTypes.string.isRequired
- // props.specialFilters: PropTypes.object.isRequired
- // props.specialFilters:
- // [Msgs] => stdClass Object
- // [icon] => glyphicon glyphicon-envelope
- // [label] => Wiadomości
- // [btns] => Array:
- // [WIADOMOSCI] => stdClass Object
- // [value] => HAS_MSGS
- // [NOWE] => stdClass Object
- // [value] => NEW_MSGS
- // [BRAK_WIAD.] => stdClass Object
- // [value] => NO_MSGS
- // [Status] => stdClass Object
- // [icon] => glyphicon glyphicon-question-sign
- // [btns] => Array:
- // [OCZEKUJACY] => stdClass Object
- // [value] => WAITING
- // [AKTYWNI] => stdClass Object
- // [value] => AKTYWNI
- // handleClick: function (event) {
- // DBG && console.log('DBG::P5UI__TableAjaxSpecialFilters::handleChange (ns:'+this.props.namespace+')', { checked: checked });
- // this.props.store.dispatch( this.props.actions.unselectAll( this.props.namespace ) )
- // },
- renderSpecialFilter: function (key) {
- var props = this.props.specialFilters[key];
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilters::renderSpecialFilter (ns:'+this.props.namespace+')', { key: key, props, state: this.state });
- if ('RELATIONS' === props.type) {
- DBG && console.warn('DBG::P5UI__TableAjaxSpecialFilters::renderSpecialFilter TODO render RELATIONS filter (ns:'+this.props.namespace+')', { props, state: this.state });
- return h(P5UI__TableAjaxSpecialFilterRelations, {
- store: this.props.store,
- actions: this.props.actions,
- name: key,
- icon: props.icon,
- label: props.label,
- availableBackRefs: props.availableBackRefs,
- availableChildRefs: props.availableChildRefs,
- });
- }
- return h(P5UI__TableAjaxSpecialFilter, {
- store: this.props.store,
- actions: this.props.actions,
- name: key,
- icon: props.icon,
- label: props.label,
- values: props.btns,
- });
- },
- render: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSpecialFilters::render (ns:'+this.props.namespace+')', { props: this.props, state: this.state });
- return h('div', {}, Object.keys(this.props.specialFilters).map(this.renderSpecialFilter))
- }
- });
- global['p5UI__TableAjaxTheadSortRow'] = function (props) {
- DBG && console.log("DBG::TableAjaxTheadFiltersRow ...", { props: props });
- // props: {
- // tblFunctions: priv.options.tblFunctions,
- // filtersClean: priv.options.filtersClean,
- // priv: priv,
- // primaryKey: _state.primaryKey,
- // checkboxes: priv.options.checkboxes,
- // namespace: priv.options.namespace,
- // selectedStore: priv.options.selectedStore,
- // selectedActions: priv.options.selectedActions,
- // filterStore: priv.options.filterStore,
- // filterActions: priv.options.filterActions,
- // colsSorted: _state.colsSorted,
- // _data_cols: _data.cols,
- // }
- var maxHeadLines = props.colsSorted.reduce(function (ret, fieldName) {
- var fieldProps = props._data_cols[fieldName];
- if (!fieldProps.friendly) return ret;
- var numLines = fieldProps.friendly.split('<br>').length; // @see SE/se-lib/TableAjax.php.p5UI__TableAjaxSortableLabel.js:convertLabelHtmlLinesToRect
- return (numLines > ret) ? numLines : ret;
- }, 1);
- var stickyCellHeight = (maxHeadLines > 2) ? 63 : (2 === maxHeadLines ? 46 : 29);
- // var stickyCellHeight = 29; // 1 line
- // var stickyCellHeight = 46; // 2 lines
- // var stickyCellHeight = 63; // 3 lines
- var outStickyCellHeight = '' + stickyCellHeight + "px";
- var addNewLines = (maxHeadLines > 1)
- ? '.'.repeat(maxHeadLines - 1).split('').map(function () { return h('br'); })
- : []
- ;
- return h(React.Fragment, {}, [
- (props.tblFunctions || props.filtersClean)
- ? h('th', { className: "text-right head-info stickyCol stickyCol1", style: { height: outStickyCellHeight } },
- addNewLines.concat(
- Object.keys(props.tblFunctions).map(function (funName) {
- var funObj = props.tblFunctions[funName];
- DBG && console.log("DBG::TableAjaxTheadFiltersRow:loop tblFunctions ...", { funName, funObj });
- var onClickName = (funObj.method && props.priv[funObj.method] && typeof props.priv[funObj.method] == 'function') ? funObj.method : null;
- return h('a', Object.assign(
- {
- href: funObj.href || '#',
- title: funObj.title,
- },
- (onClickName)
- ? { onClick: props.priv[onClickName].bind(props.priv) }
- : {}
- ), [
- (funObj.icon)
- ? h('span', { className: "glyphicon glyphicon-" + funObj.icon })
- : null
- ,
- " ",
- ]);
- // if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
- // funHtml.on('click', priv[funObj.method])
- // }
- })
- ))
- : null
- ,
- (props.primaryKey && props.checkboxes)
- ? h('th', { className: "stickyCol stickyCol2", style: { padding: "3px 5px", height: outStickyCellHeight } },
- addNewLines.concat([
- h(P5UI__TableAjaxRowCheckbox, {
- namespace: props.namespace,
- primaryKey: 'select-all',
- store: props.selectedStore,
- actions: props.selectedActions,
- }),
- ]))
- : null
- ,
- ].concat(
- props.colsSorted.map(function (fieldName, idx) {
- var fieldProps = props._data_cols[fieldName];
- DBG && console.log("DBG::TableAjaxTheadSortRow:loop fields", { fieldName, idx, fieldProps });
- if (fieldProps.hidden) return null;
- // if (_state.primaryKey === column) headCell.addClass('stickyCol stickyCol3')
- return h('th', {
- className: [
- "ta-ordering",
- (fieldName === props.primaryKey) ? "stickyCol stickyCol3" : "",
- ].join(" "),
- style: (fieldName === props.primaryKey) ? { height: outStickyCellHeight } : {},
- }, [
- h(P5UI__TableAjaxSortableLabel, {
- namespace: props.namespace,
- isSortable: (fieldProps.sortable !== false && fieldProps.type != 'special' && fieldProps.type != 'geom' && fieldProps.type != "simpleLink" && fieldProps.type != "ref"), // TODO: fieldProps.sortable
- fieldName: fieldName,
- fieldProps: fieldProps,
- store: props.filterStore,
- actions: props.filterActions,
- maxLabelLines: maxHeadLines,
- })
- ].concat(
- // hideColBtn.on('click', { column: column }, priv.columnHideClicked)
- (fieldName !== props.primaryKey)
- ? h('i', {
- className: "glyphicon glyphicon-remove remove-cell",
- // p5_data_fieldName: fieldName,
- onClick: function () {
- props.priv.hideColumn(fieldName).bind(props.priv)
- },
- })
- : null
- ,
- ));
- })
- ));
- };
- global['p5UI__TableAjaxTheadFiltersRow'] = function (props) {
- DBG && console.log("DBG::TableAjaxTheadFiltersRow ...", { props: props });
- // props: {
- // namespace: priv.options.namespace,
- // filterStore: priv.options.filterStore,
- // filterActions: priv.options.filterActions,
- // checkboxes: priv.options.checkboxes,
- // primaryKey: _state.primaryKey,
- // colsSorted: _state.colsSorted,
- // _data_cols: _data.cols,
- // rowFunctions: priv.options.rowFunctions,
- // filtersClean: priv.options.filtersClean,
- // forceFilterInit: priv.options.forceFilterInit,
- // checkboxIdContext: priv.options.checkboxIdContext,
- // }
- var cellHeight = 24;
- var stickyCellHeight = '' + (cellHeight + 1) + "px";
- return h(React.Fragment, {}, [
- (props.filtersClean)
- ? h(p5UI__TableAjaxClearAllFilters, {
- style: { padding: '0', height: stickyCellHeight },
- className: "text-right stickyCol stickyCol1",
- store: props.filterStore,
- actions: props.filterActions,
- })
- : (
- (props.rowFunctions)
- ? h('th', { className: "text-right stickyCol stickyCol1", style: { padding: '0', height: stickyCellHeight } })
- : null
- )
- ,
- (props.primaryKey && props.checkboxes)
- ? h(P5UI__TableAjaxFieldCheckboxSearch, {
- style: { padding: "0" },
- className: "stickyCol stickyCol2",
- namespace: props.namespace,
- fieldName: ( props.checkboxIdContext ? '@sel_' + props.checkboxIdContext : '@selected' ),
- store: props.filterStore,
- actions: props.filterActions
- })
- : null
- ,
- ].concat(
- props.colsSorted.map(function (fieldName, idx) {
- var fieldProps = props._data_cols[fieldName];
- DBG && console.log("DBG::TableAjaxTheadFiltersRow:loop fields", { fieldName, idx, fieldProps });
- // var tooltip = (fieldProps.filterTooltip === true) ? undefined : ((fieldProps.filterTooltip === false) ? '' : fieldProps.filterTooltip);
- // var placeHolder = (fieldProps.placeHolder === true) ? undefined : ((fieldProps.placeHolder === false) ? '' : fieldProps.placeHolder);
- if (fieldProps.hidden) return null;
- return h('th', {
- style: { padding: 0 },
- className: (1 === idx) ? "stickyCol stickyCol3" : "",
- }, [
- (true) // (fieldProps.filterable)
- ? h(p5UI__FieldInputFilterSearch, {
- disabled: (fieldProps.forceFilterInit && undefined !== fieldProps.forceFilterInit[fieldName]),
- fieldName: fieldName,
- type: fieldProps.type,
- lagacyProps: fieldProps, // TODO: use only required like xsdType
- // xsdType: fieldProps.xsdType,
- store: props.filterStore,
- onChange: function (fieldName, value) {
- props.filterStore.dispatch(props.filterActions.delayFilter(fieldName, value));
- }
- })
- : null,
- ]);
- })
- ));
- };
- global['P5UI__TableAjaxFieldCheckboxSearch'] = createReactClass({
- // props.namespace: PropTypes.string.isRequired
- // props.fieldName: PropTypes.string.isRequired
- // props.store: Redux store with state: { isLoading bool, selected array of strings }
- // props.actions: Redux store actions
- getStateFromStore: function () {
- var state = this.props.store.getState();
- // selected = || 2 // 0 - unchecked, 1 - checked, 2 - indeterminate
- var selected = '';
- if (state.filter.has(this.props.fieldName)) {
- selected = state.filter.get(this.props.fieldName)
- }
- return {
- disabled: this.props.disabled ? true : false,
- selected: selected,
- isActive: ('YES' === selected || 'NO' === selected),
- // isLoading: (-1 !== state.loading.indexOf(this.props.fieldName)),
- // checked: (-1 !== state.selected.indexOf(this.props.fieldName))
- };
- },
- getInitialState: function() {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::TableAjaxFieldCheckboxSearch::componentDidMount (f:'+this.props.fieldName+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::TableAjaxFieldCheckboxSearch::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
- this.setState(this.getStateFromStore())
- },
- shouldComponentUpdate: function (nextProps, nextState) {
- DBG && console.log('DBG::TableAjaxFieldCheckboxSearch::shouldComponentUpdate (f:'+this.props.fieldName+')', { state: this.state, nextState});
- return (
- this.state.disabled !== nextState.disabled
- || this.state.selected !== nextState.selected
- );
- },
- handleChange: function (selected) { // selected: 0 - not checked, 1 - checked, 2 - indeterminate
- DBG && console.log('DBG::TableAjaxFieldCheckboxSearch::handleChange (f:'+this.props.fieldName+')', { selected: selected, state: this.state });
- if (0 === selected) {
- this.props.store.dispatch( this.props.actions.setFilter(this.props.fieldName, 'NO') );
- } else if (1 === selected) {
- this.props.store.dispatch( this.props.actions.setFilter(this.props.fieldName, 'YES') );
- } else if (2 === selected) {
- this.props.store.dispatch( this.props.actions.setFilter(this.props.fieldName, '') );
- }
- },
- mapSelectedToValue: function (selected) {
- switch (selected) {
- case 'YES': return 1;
- case 'NO': return 0;
- default: return 2;
- }
- },
- render: function () {
- DBG && console.log('DBG::TableAjaxFieldCheckboxSearch::render (f:'+this.props.fieldName+')', { props: this.props, state: this.state, state_sel: this.state.selected, sel: this.mapSelectedToValue(this.state.selected) });
- // headCell = $('<th class="stickyCol stickyCol2" style="padding:0"></th>').appendTo(node);
- return h('th', {
- p5_node_id: "tableAjax_filters_selected",
- style: Object.assign({}, this.props.style || {}, this.state.isActive ? { backgroundColor: "#d9edf7" } : {}),
- className: this.props.className || "",
- }, [
- h('div',
- {
- style: {
- boxSizing: 'border-box', width: '100%', height: '21px', padding: '0 5px', borderTop: 0,
- borderBottom: '2px solid ' + (this.state.isActive ? '#00ACCC' : 'transparent'),
- },
- }, [
- h(p5UI__FieldCheckboxSearch, {
- size: 19,
- color: (this.state.isActive ? '#000' : '#888'),
- staticLabel: ["Pokaż:", "wszystkie,", "wybrane,", "niewybrane"].join("\n"),
- fieldName: this.props.fieldName,
- selected: this.mapSelectedToValue(this.state.selected),
- onChange: this.handleChange
- // checked: this.state.checked,
- // disabled: this.state.disabled,
- // isLoading: this.state.isLoading,
- }),
- ]
- )
- ]);
- }
- });
- global['p5UI__FieldInputFilterSearch'] = createReactClass({
- // props.fieldName: PropTypes.string.isRequired
- // props.type: PropTypes.string.isRequired
- // props.store: Redux store with state: { }
- // props.actions: Redux store actions
- // props.disabled: PropTypes.bool
- // props.lagacyProps: PropTypes.object
- getStateFromStore: function () {
- var storeState = this.props.store.getState();
- return {
- value: storeState.filter.get(this.props.fieldName) || '',
- isActive: storeState.filter.has(this.props.fieldName)
- };
- },
- getInitialState: function() {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::p5UI__FieldInputFilterSearch::componentDidMount (f:'+this.props.fieldName+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::p5UI__FieldInputFilterSearch::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
- this.setState(this.getStateFromStore())
- },
- shouldComponentUpdate: function (nextProps, nextState) {
- DBG && console.log('DBG::p5UI__FieldInputFilterSearch::shouldComponentUpdate (f:'+this.props.fieldName+')', { state: this.state, nextState});
- return (
- this.state.value !== nextState.value
- || this.state.isActive !== nextState.isActive
- );
- },
- handleChange: function (event) { // handleChange: function (event) {
- var value = event.target.value;
- DBG && console.log('DBG::p5UI__FieldInputFilterSearch::handleChange (f:'+this.props.fieldName+')', { value });
- this.setState({ value: value });
- this.props.onChange(this.props.fieldName, value);
- // this.props.store.dispatch( this.props.actions.toggle( this.props.namespace, this.props.primaryKey, checked ) )
- },
- render: function () {
- DBG && console.log('DBG::p5UI__FieldInputFilterSearch::render (f:'+this.props.fieldName+',v:'+this.state.value+')', { props: this.props, state: this.state });
- switch (this.props.type) {
- case "number":
- case "date":
- case "bool":
- case "p5:price":
- case "p5:www_link":
- case "p5:string":
- case "string": return this.renderInput();
- case "special": return this.renderEmpty();
- case "simpleLink": return this.renderEmpty();
- case "geom": return this.renderInput();
- case "none": return this.renderEmpty();
- case "ref": return this.renderEmpty();
- default: return this.renderEmpty();
- }
- },
- renderEmpty: function () {
- return h('div', {}, " ");
- },
- renderInput: function () {
- return h('input', {
- className: "filter", // + ( this.state.isActive ? " filter-isActive" : "" ),
- placeholder: !this.props.disabled ? "%" : "",
- type: "text",
- disabled: this.props.disabled || false,
- style: {
- boxSizing: 'border-box', width: '100%', height: '21px', borderTop: 0,
- borderBottom: '2px solid ' + (this.state.isActive ? "#00ACCC" : "transparent"),
- backgroundColor: (this.state.isActive ? "#d9edf7" : "#eee"),
- },
- value: this.state.value,
- onChange: this.handleChange
- });
- }
- });
- global['p5UI__TableAjaxClearAllFilters'] = createReactClass({
- // props.store: Redux store with state: { }
- // props.actions: Redux store actions
- getStateFromStore: function () {
- var storeState = this.props.store.getState();
- return {
- isActive: (storeState.filter.size > 0 || storeState.specialFilter.size > 0)
- };
- },
- getInitialState: function() {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::TableAjaxClearAllFilters::componentDidMount (f:'+this.props.fieldName+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::TableAjaxClearAllFilters::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
- this.setState(this.getStateFromStore())
- },
- // shouldComponentUpdate: function (nextProps, nextState) {
- // DBG && console.log('DBG::TableAjaxClearAllFilters::shouldComponentUpdate (f:'+this.props.fieldName+')', { state: this.state, nextState});
- // return (
- // this.state.value !== nextState.value
- // || this.state.active !== nextState.active
- // );
- // },
- handleClick: function (event) {
- DBG && console.log('DBG::TableAjaxClearAllFilters::handleClick (clearAllFilters)');
- this.props.store.dispatch( this.props.actions.clearAllFilters() )
- },
- render: function () {
- DBG && console.log('DBG::TableAjaxClearAllFilters::render (clearAllFilters)', { props: this.props, state: this.state });
- return h('th', {
- p5_node_id: "tableAjax_filters_clearAll",
- style: Object.assign({}, this.props.style || {}, this.state.isActive ? { backgroundColor: "#d9edf7" } : {}),
- className: this.props.className || "",
- }, [
- h('i', {
- title: this.props.title || "Kasuj wszystkie filtry",
- className: "glyphicon glyphicon-remove",
- style: Object.assign(
- {
- opacity: '0.5',
- lineHeight: '20px',
- padding: '0 3px',
- cursor: 'pointer',
- },
- this.state.isActive ? { color: '#f00', backgroundColor: "#d9edf7" } : { color: '#777' }
- ),
- onClick: this.handleClick
- })
- ]);
- }
- });
- var TableAjax = function() {
- var priv = {}; //private api
- var publ = {}; //public api
- priv.options = {};
- var defaults = {
- namespace: '',
- url: '', //webservice url
- urlPost: false, //use POST instead of GET
- selectAllByFilterUrl: '',
- getCsvTheGeomAjaxUrl: '',
- removeTheGeomAjaxUrl: '',
- moreFunctionsCellAjaxUrl: '',
- editInlineSaveUrl: '',
- theGeomSaveUrl: '',
- pageSizeSave: '',
- hiddenColsSaveUrl: '',
- editInlineUrl: '',
- addUserTableFilterAjaxUrl: '',
- rmUserTableFilterAjaxUrl: '',
- hasAdditionalLayers: 0,
- labelHtml: '',
- debug: false, //prints debug info to console
- filter: false, //show filter row
- filterInit: false,// init filters data
- forceFilterInit: false,
- columnPicker: false, //show columnpicker
- checkboxes: false, //show body checkboxes
- actions: '', //holds action links
- pageSize: 10, //current pagesize
- pageSizes: [10, 20, 30, 40, 50, 'All'], //available pagesizes
- hidePagerOnEmpty: false, //removes pager if no rows
- types: { //type specific options
- string: {},
- number: {},
- bool: {},
- date: {}
- },
- rowFunctions: false,
- tblFunctions: false,
- specialFilterFunctions: false,
- selectedFunctions: false,
- filtersClean: false,
- router: false,
- longDesc: false,
- exportFields: [],
- mapEditor: false, // mapEditor visible or not
- mapEditorContainer: 'window' // 'window' or 'dock'
- };
- var _reactUITableNode; // TODO: react table node
- var _uiMainContainerNode; // container holding table
- var _uiNodeSelectedInfo;
- var _uiNodeSpecialFilters;
- var _uiNodeFooterInfo;
- var _uiNode$Table; // the table jQuery node
- var _uiNodeTheadFiltersRow;
- var _uiNodeTheadSortRow;
- var _head; // table header
- var _headSort; // bool - to render table sort row in `priv.renderTable` function
- var _headFilter; // bool - to render table filter row in `priv.renderTable` function
- var _headSpecialFilter; // table header special filter row
- var _bodyNode; // table body
- var _body; // TODO: table body need render?
- var _foot; // table footer
- var _inlineEditBox; // inline edit box with form
- var _popoverCell; // inline popover cell
- var _popoverCellCurrent; // inline popover cell
- var _popoverCellAjaxXhr;
- var _mapEditor; // map editor node
- var _mapEditorWrap; // map editor wrapper node
- var _mapEditorDialog; // map editor jquery ui dialog node
- var _state = {};// state - to replace variables below (date, ...)
- var _data; //columns and rows
- var _currDpOp; // clicked datetimepicker operator
- var _filterTimeout; // timer for delayed filtering
- var _checkToggleChecked = false; // check-all toggle state
- var _exportFieldsSelect = {};
- var _tableWidth;
- var _fieldWidgets = {};
- /*
- initialize the plugin.
- */
- priv.init = function() {
- _uiMainContainerNode = priv.options.mainContainerNode; // <div id="{_htmlID}" style="..."><table class="AjaxTable...
- _state = {};// init state
- _state.page = 1;
- _state.specialFilters = {};
- { // init events
- jQuery(_uiMainContainerNode).on('TableAjax:render', priv.onRender);
- jQuery(window).on('resize', priv.onWindowResize)
- }
- priv.initialRender();// set up _uiNode$Table, ...
- priv.options.types.string = ((priv.options.types || {}).string || {});
- priv.options.types.number = ((priv.options.types || {}).number || {});
- priv.options.types.bool = ((priv.options.types || {}).bool || {});
- priv.options.types.date = ((priv.options.types || {}).date || {});
- if (priv.options.mapEditorContainer != 'dock'
- && priv.options.mapEditorContainer != 'window') {
- priv.options.mapEditorContainer = 'window';
- }
- if (priv.options.exportFields) {
- $.each(priv.options.exportFields, function(ind, col) {
- _exportFieldsSelect[col] = true;
- });
- }
- _state._forceFilterQuery = p5Utils__objectToQueryWithKeyPrefix(priv.options.forceFilterInit, 'f_')
- var fetchDataPromise = (function (props) {
- var props = props || {};
- return function (namespace, filterParams) {
- var urlAdd = '';
- DBG && console.log('DBG: fetchDataPromise', props.url)
- return window.fetch(props.url + urlAdd, {
- method: 'GET', // priv.options.urlPost ? 'POST' : 'GET',
- credentials: 'same-origin',// add cookies
- }).then(function (response) {
- // TODO: handle parse json error
- return response.json()
- }).then(function (responseJson) {
- // if (priv.options.debug || DBG) console.log('loadDataAjax:fetch:loadPage: request finished, data:', data);
- // // props.notify(data);
- if ('success' !== responseJson.type) throw responseJson.msg || "Wystąpił problem podczas pobierania danych";
- // state = {data: {}};
- // state.data.cols = data.cols || {};
- // state.data.rows = data.rows || [];
- // state.data.total = data.total || 0;
- // state.data.primaryKey = data.primaryKey || 'ID';
- // state.page = data.page || 0;
- // state.pageSize = data.pageSize || priv.options.pageSize;
- // state.filters = data.filters || {};
- // DBG && console.log('DBG::loadPage... - FETCH_DATA END priv.setState(state);', { state });
- // priv.setState(state);
- // _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
- // } else {
- // props.notify(data);
- // props.showFailFetchDataMsg();
- // }
- return responseJson;
- }).then(function (responseData) {
- DBG && console.log('DBG: fetchDataPromise responseData', { responseData })
- var colsOrder = []; // responseData.cols.index
- return {
- rawReponse: responseData,
- colsOrder: colsOrder,
- rows: responseData.rows,
- }
- }).catch(function (err) {
- props.notify({ type: 'error', msg: ''+err });
- props.showFailFetchDataMsg();
- });
- };
- })({
- url: priv.options.url,
- showFailFetchDataMsg: priv.showFailFetchDataMsg.bind(priv),
- notify: p5UI__notifyAjaxCallback,
- });
- var stateObjectTableData = createTableDataStateObject({}, fetchDataPromise);
- DBG && console.log('DBG: stateObjectTableData', stateObjectTableData);
- priv.options.tableDataStore = stateObjectTableData.store;
- priv.options.tableDataActions = stateObjectTableData.actions;
- var stateObjectFilter = createTableFiltersStateObject(priv.options.filterInit || {});
- priv.options.filterStore = stateObjectFilter.store;
- priv.options.filterActions = stateObjectFilter.actions;
- priv.filter_mapStoreToState = function (curFilterState) {
- // var curFilterState = store.getState()
- return {
- _filterQuery: p5Utils__mapToQueryWithKeyPrefix(curFilterState.filter, 'f_'),
- _specialFilterQuery: p5Utils__mapToQueryWithKeyPrefix(curFilterState.specialFilter, 'sf_'),
- _currSortCol: curFilterState.currSortCol,
- _currSortFlip: curFilterState.currSortFlip
- };
- };
- priv.filter_getFilterQuery = function () {
- return [
- _state._filterQuery,
- _state._specialFilterQuery,
- _state._forceFilterQuery
- ].filter(Boolean).join('&');
- };
- priv.filter_getFullFilterQuery = function () {
- return [
- 'currSortCol=' + ( _state._currSortCol || ''),
- 'currSortFlip=' + ( _state._currSortFlip ? "desc" : "asc" ),
- _state._filterQuery,
- _state._specialFilterQuery,
- _state._forceFilterQuery
- ].filter(Boolean).join('&');
- };
- _state = Object.assign(_state, priv.filter_mapStoreToState(priv.options.filterStore.getState()));
- DBG && console.log('TODO:INIT: ', { _state });
- priv.options.filterStore.subscribe(function () {
- var curState = priv.filter_mapStoreToState(priv.options.filterStore.getState());
- var needFetchData = (
- curState._filterQuery !== _state._filterQuery
- || curState._specialFilterQuery !== _state._specialFilterQuery
- || curState._currSortCol !== _state._currSortCol
- || curState._currSortFlip !== _state._currSortFlip
- );
- DBG && console.log('TODO:filtersUpdated - FETCH_DATA: ', { _state, curState });
- _state._filterQuery = curState._filterQuery;
- _state._specialFilterQuery = curState._specialFilterQuery;
- _state._currSortCol = curState._currSortCol;
- _state._currSortFlip = curState._currSortFlip;
- if (needFetchData) {
- DBG && console.log('TODO:filtersUpdated - FETCH_DATA: ', { curState });
- priv.loadPage(0)
- }
- })
- if (priv.options.checkboxes) {
- var stateObjectSelected = createTableSelectedStateObject(priv.options.checkboxIdContext);
- priv.options.selectedStore = stateObjectSelected.store;
- priv.options.selectedActions = stateObjectSelected.actions;
- if (_uiNodeSelectedInfo) { // must run after priv.initialRender(); - _uiNodeSelectedInfo must exists
- ReactDOM.render(
- h(P5UI__TableAjaxSelectedInfo, {
- namespace: priv.options.namespace,
- store: priv.options.selectedStore,
- actions: priv.options.selectedActions,
- tools: priv.options.selectedFunctions,
- onSelectAllMatching: function () {
- // TODO: priv.filter_mapStoreToState(priv.options.filterStore.getState())
- var filterQuery = priv.filter_getFilterQuery();
- // var filterQuery = '';
- // filterQuery += (_state._filterQuery) ? "&" + _state._filterQuery : "";
- // filterQuery += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
- // filterQuery += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
- priv.options.selectedStore.dispatch( priv.options.selectedActions.selectAllMatchingFilter(priv.options.namespace, filterQuery) );
- }
- }),
- _uiNodeSelectedInfo
- );
- }
- }
- priv.initialReactRender(RENDER_AS_REACT); // set up _reactUITableNode, require stores created
- // TODO: priv.options.router.init();
- // priv.options.router.getLinkOnclickFunction(task, args);
- if (typeof priv.options.router == "function") {
- if (location.hash) {
- priv.options.router()
- } else {
- priv.update(priv.options.router)
- }
- $(window).bind('hashchange', function() {
- priv.options.router();
- });
- } else {
- priv.update()
- }
- };
- priv.onRender = function(e) {
- var renderUIParts = [];
- if (arguments.length > 1) {
- for (var i=1; i<arguments.length; i++) {
- renderUIParts.push( arguments[i] );
- }
- }
- if (priv.options.debug || DBG) console.log('onRender.arguments:', arguments.length, arguments, 'e:', e);
- DBG && console.log('DBG::onRender: ', { renderUIParts });
- // console.log("priv.onRender arguments:", arguments);
- // console.trace();
- renderUIParts.forEach(function (uiPart) {
- switch (uiPart) {
- case 'head': _head = undefined; break;
- case 'body': _body = undefined; break;
- case 'foot': _foot = undefined; break;
- case 'foot_pagination': {
- priv.renderFooterInfo();
- priv.renderFooterPagination();
- priv.renderFooterPageSizes();
- }
- break;
- case 'footer__toolbar__info': priv.renderFooterInfo(); break;
- case 'footer__toolbar__pagination': priv.renderFooterPagination(); break;
- case 'footer__toolbar__pagesizes': priv.renderFooterPageSizes(); break;
- case 'foot__columnPicker': priv.renderFooterColumnPicker(); break;
- case 'head__specialFilters': priv.renderHeadSpecialFilters(); break;
- }
- })
- priv.renderTable();
- priv.onWindowResize();
- {// activate saveBtn if some columns hidden
- var selectedFilter = priv.modelColFilter_getSelected();
- if (null === selectedFilter) {
- priv.modelColFilter_getSaveBtn().prop("disabled", false)
- } else {
- priv.modelColFilter_getSaveBtn().prop("disabled", true)
- }
- }
- };
- priv.onWindowResize = function() {
- var stickyCol1Width = priv.getStickyCol1Width();
- var stickyCol2Width = priv.getStickyCol2Width();
- var stickyCol3Width = priv.getStickyCol3Width();
- var contW = jQuery(_uiMainContainerNode).parent().width();
- var colsW = stickyCol1Width + stickyCol2Width + stickyCol3Width;
- jQuery(_uiMainContainerNode).css({width:'' + (contW - colsW) + 'px'})//, marginLeft:'' + colsW + 'px', overflowX:'scroll', overflowY:'visible', paddingBottom:'1px'});
- var wh = jQuery(window).height(); // returns height of browser viewport
- var dh = jQuery(document).height(); // returns height of HTML document (same as pageHeight in screenshot)
- if (dh > wh) {
- jQuery(_uiMainContainerNode).doubleScroll()
- jQuery(_uiMainContainerNode).prev('.doubleScroll-scroll-wrapper').css({float: 'right', display:'block'})
- } else {
- jQuery(_uiMainContainerNode).prev('.doubleScroll-scroll-wrapper').css({display:'none'})
- }
- }
- priv.uiFixStickyCols = function () {
- var stickyCol1Width = priv.getStickyCol1Width();
- var stickyCol2Width = priv.getStickyCol2Width();
- var stickyCol3Width = priv.getStickyCol3Width();
- if (undefined === _tableWidth) {
- _tableWidth = true;
- var contW = jQuery(_uiMainContainerNode).width();
- var th1 = _uiNode$Table.find('.stickyCol1:first');
- var th2 = th1.next();
- var th1W = th1.innerWidth();
- var th2W = 50 + 2 * 5;//th2.innerWidth();
- // var colsW = stickyCol1Width + stickyCol2Width + stickyCol3Width;
- var colsW = priv.getStickyColsSumWidth();
- jQuery(_uiMainContainerNode).css({
- width: '' + (contW - colsW) + 'px',
- marginLeft: '' + colsW + 'px',
- minHeight: '360px',
- overflowX: 'scroll',
- overflowY: 'visible',
- paddingBottom: '1px',
- clear: 'both',
- });
- }
- _uiNode$Table.find('.stickyCol1').css({
- position: 'absolute',
- left: '0',
- top: 'auto',
- width: '' + (stickyCol1Width) + 'px',
- });
- { // fix thead sort cols height
- // var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
- // _uiNode$Table.find('.sort').find('.stickyCol').css({height: sortStickyColHeight + 'px'});
- }
- { // fix thead filter cols height
- // var filterStickyColHeight = _uiNode$Table.find('.filter').find('th:last').outerHeight() + 1;
- // _uiNode$Table.find('.filter').find('.stickyCol').css({height: filterStickyColHeight + 'px'});
- }
- if (priv.options.checkboxes) _uiNode$Table.find('.stickyCol2').css({
- position: 'absolute',
- left: '' + (stickyCol1Width) + 'px',
- top: 'auto',
- width: '' + (stickyCol2Width) + 'px',
- borderRight: '1px solid silver',
- overflow: 'hidden'
- });
- _uiNode$Table.find('.stickyCol3').css({
- position: 'absolute',
- left: '' + (stickyCol1Width + stickyCol2Width) + 'px',
- top: 'auto',
- width: '' + (stickyCol3Width) + 'px',
- borderRight: '1px solid silver',
- overflow: 'hidden'
- });
- _uiNode$Table.find('tbody').find('.stickyCol').css({
- height: '' + (29 + 1) + 'px',
- });
- };
- priv.getStickyCol1Width = function () { return (12 + 3) * 4 + 2 * 5 + 1; }
- priv.getStickyCol2Width = function () { return (priv.options.checkboxes) ? 20 + 2 * 5 + 1 : 0; }
- priv.getStickyCol3Width = function () { return 50 + 2 * 5 + 1; }
- priv.getStickyColsSumWidth = function () { return priv.getStickyCol1Width() + priv.getStickyCol2Width() + priv.getStickyCol3Width(); }
- priv.initialReactRender = function (isVisible) { // TODO: render table as React node
- if (!isVisible) return; // TODO: double request fetchData BUG `_task=loadDataAjax` - second request send without filter/sort
- _reactUITableNode = document.createElement('div')
- if (!isVisible) _reactUITableNode.style.display = 'none';
- _reactUITableNode.setAttribute('class', "TableAjax-reactUITableNode");
- _uiMainContainerNode.parentNode.appendChild(_reactUITableNode);
- ReactDOM.render(
- h(p5UI__TableAjaxWidget, {
- namespace: priv.options.namespace,
- dataStore: priv.options.tableDataStore,
- dataActions: priv.options.tableDataActions,
- filterStore: priv.options.filterStore,
- filterActions: priv.options.filterActions,
- selectedStore: priv.options.selectedStore,
- selectedActions: priv.options.selectedActions,
- }),
- _reactUITableNode
- );
- };
- priv.initialRender = function() {
- /**
- <topWrap /> <!-- _uiNodeSelectedInfo | _uiNodeSpecialFilters -->
- <afterTopWrap /> <!-- for clear:both, border and padding -->
- <_uiMainContainerNode>
- <_uiNode$Table>
- <_head>
- <_uiNodeTheadSortRow />
- <_uiNodeTheadFiltersRow />
- </_head>
- <_bodyNode />
- <tfoot /> <!-- @todo: empty? not used? -->
- </_uiNode$Table>
- </_uiMainContainerNode>
- <_foot /> <!-- @class="foot tblAjax__footer": total | pagination | ui table functions -->
- <tblAjax__inlineEditBox/>
- <_mapEditorWrap />
- <_popoverCell />
- */
- _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiMainContainerNode);
- _head = $('<thead></thead>').prependTo(_uiNode$Table);
- _uiNodeTheadSortRow = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head).get(0);
- _uiNodeTheadFiltersRow = $('<tr class="filter tblAjax__head__filter" p5_node_id="tblAjax_filters"></tr>').appendTo(_head).get(0);
- _bodyNode = $('<tbody></tbody>').insertAfter(_head);
- $('<tfoot></tfoot>').insertAfter(_bodyNode);
- _foot = $('<div class="foot tblAjax__footer" style="margin:0; padding:12px; border-top:1px solid #ddd; border-bottom:1px solid #ddd"></div>').insertAfter(_uiMainContainerNode);
- {
- var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar" style="margin:0"></div>').appendTo(_foot);
- _uiNodeFooterInfo = document.createElement('div') // .tblAjax__head__specialFilter
- _uiNodeFooterInfo.setAttribute('class', "tblAjax__footer__toolbar__info foot-info");
- _uiNodeFooterInfo.style.float = "left";
- _uiNodeFooterInfo.style.padding = "0 20px 0 0";
- $(_uiNodeFooterInfo).appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__pagination"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__pagesizes"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__columnPicker"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__functions"></span>').appendTo(footToolbar);
- $('<span class="tblAjax__footer__toolbar__export"></span>').appendTo(footToolbar);
- }
- _mapEditorWrap = $('<div class="mapEditor" style="display:none"></div>').insertAfter(_foot);
- _mapEditor = $('<div class="mapEditor-map"></div>').appendTo(_mapEditorWrap);
- _popoverCell = $('<div class="popoverCell" style="display:none"></div>').insertAfter(_foot);
- $('<div class="tblAjax__inlineEditBox"></div>').insertAfter(_foot);
- _uiNodeSelectedInfo = document.createElement('div')
- _uiNodeSpecialFilters = document.createElement('div') // .tblAjax__head__specialFilter
- var topWrap = document.createElement('div')
- {
- var topLeftWrap = document.createElement('div')
- var topRightWrap = document.createElement('div')
- topWrap.setAttribute('p5_node_id', "tblAjax_topWrap")
- topWrap.appendChild(topLeftWrap)
- topWrap.appendChild(topRightWrap)
- topWrap.style.padding = '12px 0'
- topWrap.style.borderTop = '1px solid #ddd'
- topLeftWrap.style.width = '' + priv.getStickyColsSumWidth() + 'px'
- topLeftWrap.style.float = 'left'
- topLeftWrap.style.fontSize = '12px'
- topLeftWrap.style.lineHeight = '22px'
- topRightWrap.style.float = 'left'
- topLeftWrap.appendChild(_uiNodeSelectedInfo)
- topRightWrap.appendChild(_uiNodeSpecialFilters)
- }
- _uiMainContainerNode.parentNode.insertBefore(topWrap, _uiMainContainerNode)
- var afterTopWrap = document.createElement('div')
- {
- afterTopWrap.setAttribute('p5_node_id', "tblAjax_afterTopWrap")
- afterTopWrap.style.paddingTop = '12px'
- afterTopWrap.style.borderBottom = '1px solid #ddd'
- afterTopWrap.style.clear = 'both'
- }
- _uiMainContainerNode.parentNode.insertBefore(afterTopWrap, _uiMainContainerNode)
- priv.renderInlineEditBox();// .tblAjax__inlineEditBox
- _foot = undefined;
- _head = undefined;
- _body = undefined;
- };
- priv.renderTable = function() {
- if (!_state.colsSorted) return;
- DBG && console.warn('DBG:renderTable: ', { _head, _headSort, _headFilter, _headSpecialFilter });
- if (!_head) {
- _headSort = undefined;
- _headFilter = undefined;
- _headSpecialFilter = undefined;
- _head = _uiNode$Table.find('thead');
- }
- if (!_headSort) {
- priv.renderTableTheadSort();
- _headSort = true;
- }
- if (!_headFilter && priv.options.filter) {
- priv.renderTableTheadFilter();
- _headFilter = true;
- }
- if (!_headSpecialFilter && priv.options.specialFilterFunctions) {
- priv.renderHeadSpecialFilters();
- _headSpecialFilter = true;
- }
- if (!_body) {
- DBG && console.log('DBG:renderTable !_body', { _bodyNode })
- // _uiNode$Table.find('tbody').remove();
- // _bodyNode = $('<tbody></tbody>').insertAfter(_head);
- // _uiNode$Table.find('tbody > tr').remove();
- _bodyNode.find('tr').remove();
- var rowsAdded = Math.min(_data.rows.length, priv.options.pageSize);
- _data.rows.slice(0, rowsAdded).forEach(function (props) {
- var rowNode = priv.renderRow(props);
- if (rowNode) rowNode.appendTo(_bodyNode);
- })
- for (var i = rowsAdded; i < priv.options.pageSize; i++) {
- priv.renderRowEmptyNode().appendTo(_bodyNode);
- }
- }
- if (!_foot) {
- priv.renderTableTfoot();
- priv.renderFooter();
- }
- _foot = $(_uiMainContainerNode).next('.foot');
- priv.uiFixStickyCols();
- if (_data.total == 0 && priv.options.hidePagerOnEmpty) {
- $('.btn-toolbar', _foot).remove();
- }
- if (priv.options.debug || DBG) console.log('table created');
- if (typeof priv.options.tableCreated == 'function') {
- priv.options.tableCreated.call(_uiNode$Table.get(0), {table: _uiNode$Table.get(0)});
- }
- };
- // TODO: priv.renderFieldWidget_InlineEdit = function(fldName, value) {}
- // TODO: priv.renderFieldWidget_FormField = function(fldName, value) {}
- // @usage: priv.renderFieldWidget_TableCell(fldName, val, rowPK, row)
- priv.renderFieldWidget_TableCell = function(fldName, value, rowPK, row) {
- var renderFieldAsTableCell = priv.getFieldWidget_TableCell(fldName);
- if (!renderFieldAsTableCell) return null;
- return renderFieldAsTableCell(value, rowPK, row);
- };
- priv.registerFieldWidget = function(type, fldName, fieldProps) {
- var fieldWidget = null;
- switch (type) {
- case "date":// @return Element - TODO: not used yet
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps;
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- return val;
- }
- }(fldName, fieldProps));
- break;
- case "bool":// @return Element - TODO: not used yet
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps;
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- fldNode = document.createElement('input');
- fldNode.setAttribute('type', 'checkbox');
- if (val) fldNode.setAttribute('checked', 'checked');
- fldNode.setAttribute('disabled', 'disabled');
- fldNode.appendChild(document.createTextNode(val));
- return fldNode;
- }
- }(fldName, fieldProps));
- break;
- case "number":// @return String - TODO: not used yet
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps,
- _fractionDigits = _.get(_fieldProps, 'fractionDigits', 2);
- // console.log('FieldWidget: generate function to render field('+_fieldName+') _fractionDigits('+_fractionDigits+')', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- if ('' === val) return ''; // is nullable
- if ('*****' === val) return val;
- // enumeration
- // fractionDigits
- // maxExclusive
- // maxInclusive
- // minExclusive
- // minInclusive
- // pattern
- // totalDigits
- // whiteSpace
- val = Number(val);
- return ((val || 0) % 1 === 0)? val : val.toFixed(_fractionDigits);
- }
- }(fldName, fieldProps));
- break;
- case "string":// @return String
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps,
- _format = _.get(_fieldProps, 'format', '{0}');
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- return p5Utils__format(_format, [val]);
- }
- }(fldName, fieldProps));
- break;
- case "p5:price":// @return String
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps,
- _format = _.get(_fieldProps, 'format', '<span style="text-align:right">{0}</span>');
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- return p5Utils__format(_format, [val]);
- }
- }(fldName, fieldProps));
- break;
- case "p5:string":// @return String
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName;
- var _fieldProps = fieldProps;
- var _formatDefault = _.get(_fieldProps, 'format', null);
- var _formatByValue = _.get(_fieldProps, 'formatByValue', null);
- var _formatEmpty = _.get(_fieldProps, 'formatEmpty', null);
- var _aliasMap = _.get(_fieldProps, 'aliasMap', null);
- return function(val, fieldPK, row) {
- var outValue = '';
- if (_formatByValue && val in _formatByValue) {
- outValue = p5Utils__format(_formatByValue[val], [val])
- }
- else if (val && _formatDefault) {
- outValue = p5Utils__format(_formatDefault, [val])
- }
- else if (!val && _formatEmpty) {
- outValue = p5Utils__format(_formatEmpty, [])
- }
- // console.log('p5:string value', val, '_aliasMap', _aliasMap)
- if (_aliasMap) {
- Object.keys(_aliasMap).map(function (mapKey) {
- var mapField = _aliasMap[mapKey]
- if (undefined !== row[mapField]) {
- outValue = outValue.replace(new RegExp('\{' + mapKey + '\}', 'g'), row[mapField]);
- }
- })
- }
- return outValue;
- }
- }(fldName, fieldProps));
- break;
- case "p5:www_link":// @return Element
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName;
- var _fieldProps = fieldProps;
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- var link = '',
- a = null,
- dbg = false;
- if (!val.length) return '';
- if ('index.php' == val.substr(0, 9) || 'procesy5.php' == val.substr(0, 12)) {
- link = window.location.protocol + '//' + window.location.hostname
- link += window.location.pathname.split('/').slice(0, -1).join('/')
- link += '/' + val
- } else {
- if ('http' == val.substr(0, 4)) link = val
- //else if ('ftp' == val.substr(0, 3))
- else link = 'http://' + val
- }
- var linkErrors = validate({www_link: link}, {www_link: {url: true}});
- if (linkErrors) {
- // if(dbg)console.log('linkErrors for (' + link +')', linkErrors);
- return val;
- }
- fldNode = document.createElement('a');
- fldNode.setAttribute('href', link);
- fldNode.setAttribute('target', '_blank');
- fldNode.appendChild(document.createTextNode(val));
- return fldNode;
- }
- }(fldName, fieldProps));
- break;
- case "p5:link":// @return Element
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName;
- var _fieldProps = fieldProps;
- DBG && console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- DBG && console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- // fieldProps._appInfo.simpleLink: {
- // @href: "index.php?MENU_INIT=POKAZ_OFERTY_AKTUALNE_FUNC&task=activate_deal&id_deal={ID}"
- // @label: "Aktywuj umowę {ID}"
- // @target: "_blank"
- if (!_fieldProps._appInfo.simpleLink) return 'BUG: missing _appInfo.simpleLink!';
- if (!_fieldProps._appInfo.simpleLink['@label']) return 'BUG: missing _appInfo.simpleLink[@label]!';
- var label = p5Utils__multiReplaceValues(_fieldProps._appInfo.simpleLink['@label'], row);
- var relativeLink = p5Utils__multiReplaceValues(_fieldProps._appInfo.simpleLink['@href'], row);
- if ('index.php' == relativeLink.substr(0, 9) || 'procesy5.php' == relativeLink.substr(0, 12)) {
- link = window.location.protocol + '//' + window.location.hostname
- link += window.location.pathname.split('/').slice(0, -1).join('/')
- link += '/' + relativeLink
- } else if ('http' == relativeLink.substr(0, 4)) {
- link = relativeLink
- // else if ('ftp' == val.substr(0, 3))
- } else {
- link = 'http://' + relativeLink
- }
- var linkErrors = validate({www_link: link}, {www_link: {url: true}});
- if (linkErrors) {
- DBG && console.log('DBG:linkErrors (' + _fieldName + ': ' + link + ')', linkErrors);
- return label;
- }
- fldNode = document.createElement('a');
- fldNode.setAttribute('href', link);
- if (_fieldProps._appInfo.simpleLink['@target']) fldNode.setAttribute('target', _fieldProps._appInfo.simpleLink['@target']);
- fldNode.appendChild(document.createTextNode(label));
- return fldNode;
- }
- }(fldName, fieldProps));
- break;
- case "special":
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName;
- var _fieldProps = fieldProps;
- var _format = _.get(_fieldProps, 'format', '{0}');
- var _aliasMap = _.get(_fieldProps, 'aliasMap', null);
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps, 'row', row);
- var format = _format;
- if (_aliasMap) {
- Object.keys(_aliasMap).map(function (mapKey) {
- var mapField = _aliasMap[mapKey]
- if (undefined !== row[mapField]) {
- format = format.replace(new RegExp('\{' + mapKey + '\}', 'g'), row[mapField]);
- }
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') _aliasMap:', _aliasMap, 'row['+mapField+']', row[mapField], 'converted val:', val);
- })
- }
- return p5Utils__format(format, [val]);
- }
- }(fldName, fieldProps));
- break;
- case "simpleLink":
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps,
- _format = _.get(_fieldProps, 'format', '{0}');
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- var valLink = String(val);
- if (undefined !== _fieldProps._tsRetId
- && (0 === _fieldProps._tsRetId || '0' === _fieldProps._tsRetId || null === _fieldProps._tsRetId)
- && undefined !== _fieldProps._tsSimpleLink) {
- valLink = _fieldProps._tsSimpleLink.format;
- $.each(_fieldProps._tsSimpleLink.aliasMap, function(i, v) {
- // console.log('simpleLink aliasMap fldName:', fldName, 'i:', i, 'v:', v, 'row['+v+']', row[v], 'val', val, 'typeof val', typeof val);
- if (undefined !== row[v]) {
- var _itemValue = row[v];
- if (fldName == 'LINK_PROBLEMS' && row[v]) _itemValue = _itemValue.replace(/"/g, '%22').replace(/&/g, '%26');
- valLink = valLink.replace(new RegExp('\{' + i + '\}', 'g'), _itemValue);
- }
- });
- }
- return p5Utils__format(_format, [valLink]);
- }
- }(fldName, fieldProps));
- break;
- case "gml:PolygonPropertyType":
- case "gml:LineStringPropertyType":
- case "gml:PointPropertyType":
- case "p5Type:polygon":
- case "p5Type:lineString":
- case "p5Type:point":
- case "geom":
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps,
- _format = _.get(_fieldProps, 'format', '{0}');
- // console.log('FieldWidget: generate function to render field('+_fieldName+') ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: run function to render field('+_fieldName+') with value('+val+') ', fieldProps);
- // console.log('FieldWidget: test priv', priv);
- var node = jQuery('<span></span>');
- node.TableAjaxGeomField({
- recordID: fieldPK,
- fieldValue: val,
- hasValueClassName: 'cell-mapfld-hasValue',
- linkClassNamePrefix: 'cell-mapfld',
- linkSelectClassName: 'select',
- linkSelectAddClassNames: 'glyphicon glyphicon-map-marker',
- getCsvUrl: priv.options.getCsvTheGeomAjaxUrl,
- linkGetCsvAddClassNames: 'glyphicon glyphicon-download',
- linkRemoveClassName: 'remove',
- linkRemoveAddClassNames: 'glyphicon glyphicon-remove',
- onSelect: function(recordID, geomShape) {
- if (priv.options.debug || DBG) console.log('recordID:', recordID, 'geomShape:', geomShape);
- priv.mapEditorShow();
- _mapEditor.TableAjaxMapSelectRecord(recordID, geomShape);
- },
- onRemove: function(geomField, recordID, geomShape) {
- if (confirm('Czy usunąć obiekt z mapy dla rekordu ' + recordID + '?')) {
- if (!recordID) return;
- var selectedRecordId = recordID;
- superagent
- .post(priv.options.removeTheGeomAjaxUrl)
- .type('json') // header ĺapplication/x-www-form-urlencoded' requires type('form');
- .send({
- ID: recordID,
- namespace: priv.options.namespace
- })
- .set('Accept', 'application/json')
- .end(function(err, res) {
- if(priv.options.debug)console.log('DBG: res:', res, 'res.body:', res.body);
- var payload;
- if (err || !res.ok || 'application/json' !== res.type) {
- payload = {type: 'warning', msg: res.body.msg || 'Wystąpiły błędy', body: res.body};
- } else {
- payload = {type: 'success', msg: res.body.msg || '', body: res.body};
- }
- p5UI__notifyAjaxCallback(payload);
- var data = res.body;
- if (data && data.record && data.record.the_geom) {
- if (priv.options.debug || DBG) console.log('data.record.the_geom:2:', data.record.the_geom);
- geomField.setValue(data.record.the_geom);
- }
- else if (data && data.record) {
- if (priv.options.debug || DBG) console.log('data.record.the_geom:2:', data.record.the_geom);
- geomField.setValue(data.record.the_geom);
- }
- _mapEditor.TableAjaxMapRefresh();
- });
- }
- }
- });
- return node;
- }
- }(fldName, fieldProps));
- break;
- case "ref":
- fieldWidget = (function(fldName, fieldProps) {
- var _fieldName = fldName,
- _fieldProps = fieldProps;
- // console.log('FieldWidget: generate function to render field('+_fieldName+') fieldProps: ', fieldProps);
- return function(val, fieldPK, row) {
- // console.log('FieldWidget: pk('+fieldPK+') run function to render field('+_fieldName+') with value: ', val, ', fieldProps: ', fieldProps);
- // if (val.length > 5) return '('+val.length+')' + printFirst5 + '...' => open more info
- return _.map(val, function(v) {
- if (!v || !v.xlink) return '';
- var idRemote = v.xlink.split('.').pop()
- var nsRemote = v.xlink.split(':').pop().split('.').shift()
- var seLink = URI_BASE + 'index.php?_route=ViewTableAjax&namespace=' + fieldProps.xsdRefNsPrefix.replace(/__x3A__/g, '/') + '/' + nsRemote + '#EDIT/' + idRemote;
- var wfsLink = fieldProps.xsdRefUri + '#' + fieldProps.xsdRefType + '.' + idRemote;
- return '<a class="btn btn-xs btn-default" href="' + seLink + '" title="' + wfsLink + '">' + idRemote + '</a>';
- }).join(' ');
- }
- }(fldName, fieldProps));
- break;
- }
- _fieldWidgets[fldName] = fieldWidget;
- };
- priv.getFieldWidget_TableCell = function(fieldName) {
- var props = _data.cols[fieldName],
- type = null,
- renderFieldAsTableCell = null;
- if (!props) return null;
- type = _.get(props, 'type');
- if (!type) type = 'string';// TODO: throw Exception? / default string
- renderFieldAsTableCell = _.get(_fieldWidgets, fieldName);
- if (renderFieldAsTableCell) return renderFieldAsTableCell;
- priv.registerFieldWidget(type, fieldName, props);
- renderFieldAsTableCell = _.get(_fieldWidgets, fieldName);
- if (!renderFieldAsTableCell) throw "Field type '" + type + "' not implemented";
- return renderFieldAsTableCell;
- };
- priv.renderRow = function(props) {
- var rowNode = $('<tr></tr>');
- var rowPK = (_state.primaryKey in props) ? props[_state.primaryKey] : null;
- var cellNode;
- var columnName, columnProps, val, cellCnt, format, showTooltip, fldWidgetNode;
- var dbg = (priv.options.debug || DBG);
- // ondrop="drop_handler(event);" ondragover="dragover_handler(event);" ondragend="dragend_handler(event);"
- rowNode.attr('ondrop', "p5TA_onDrop(event, '"+rowPK+"', '"+priv.options.namespace+"')")
- rowNode.attr('ondragover', "p5TA_onDragOver(event, this, '"+rowPK+"', '"+priv.options.namespace+"')")
- rowNode.attr('ondragend', "p5TA_onDragEnd(event, this, '"+rowPK+"', '"+priv.options.namespace+"')")
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- cellNode = priv.renderCellRowFunctions(priv.options.rowFunctions, rowPK, props);
- cellNode.addClass('text-right stickyCol stickyCol1');
- cellNode.appendTo(rowNode);
- }
- //create checkbox
- if (_state.primaryKey && priv.options.checkboxes) { // row checkbox cell
- var checkable = props['checkable'] === false ? 'disabled' : '';
- cellNode = $('<td class="stickyCol stickyCol2" style="padding:3px 5px"></td>').appendTo(rowNode);
- ReactDOM.render(
- h(P5UI__TableAjaxRowCheckbox, {
- namespace: priv.options.namespace,
- primaryKey: rowPK,
- store: priv.options.selectedStore,
- actions: priv.options.selectedActions
- }),
- cellNode.get(0)
- );
- }
- if (_state.primaryKey) rowNode.data('unique', rowPK);
- //create cells
- for (var i = 0; i < _state.colsSorted.length; i++) {
- columnName = _state.colsSorted[i];
- columnProps = _data.cols[columnName];
- val = '';
- if (!columnProps) continue;
- if (columnProps.hidden) continue;// TODO: "unique" is hidden
- showTooltip = true;
- val = props[columnName];
- cellNode = $('<td></td>').appendTo(rowNode);
- if (i === 1) cellNode.addClass('stickyCol stickyCol3');// primaryKey(ID)
- if (i !== 1) cellNode.on('dblclick', {id:rowPK, col:columnName}, priv.rowDblClicked);
- cellCnt = (i === 1)? '<div></div>' : '<span></span>';
- cellCnt = $(cellCnt).appendTo(cellNode);// fix dblclick for copy
- cellNode.data('column', columnName);
- if (val === undefined) continue;
- format = _.get(columnProps, 'format', '{0}');
- // test use field widgets
- fldWidgetNode = priv.renderFieldWidget_TableCell(columnName, val, rowPK, props);
- if (fldWidgetNode || fldWidgetNode === 0) {
- cellCnt.empty();
- cellCnt.append(fldWidgetNode);
- } else if (fldWidgetNode === '') {
- cellCnt.empty();
- } else {
- console.log('TODO: !FieldWidget for row.pk('+rowPK+') col('+columnName+') typeof fldWidgetNode(' + (typeof fldWidgetNode) + ') columnProps', columnProps, 'fldWidgetNode', fldWidgetNode, 'value', props[columnName]);
- }// test fld widgets
- if (columnProps._tsRetId) {
- showTooltip = false;
- if (columnProps._tsRetId > 0) {
- cellCnt.on('click', {id:rowPK, col:columnName, friendly:columnProps.friendly, value:p5Utils__format(format, [val])}, priv.popoverCellTypeSpecial);
- }
- }
- if ('ref' === columnProps.type) showTooltip = false;
- if ('ref' === columnProps.type) cellNode.css('padding', "3px")
- if ('ref' === columnProps.type && (priv.options.debug || DBG)) console.log('renderRow rowPK('+rowPK+') columnProps', columnProps)
- // if ('ref' === columnProps.type) cellNode.html('<a href="index.php?_route=ViewTableAjax' +
- // '&namespace=' + columnProps.xsdRefNsPrefix.replace('__x3A__', '/') + '/' + columnProps.xsdRefType +
- // '&backRefNS=' + priv.options.namespace +
- // '&backRefPK=' + rowPK +
- // '&backRefField=' + columnProps.column +
- // '">przeglądaj</a>')
- if ('ref' === columnProps.type) {
- cellNode.html('<a onClick="return p5UI__tableAjaxOpenRefCell(' +
- '\'' + columnProps.xsdRefNsPrefix.replace('__x3A__', '/') + '/' + columnProps.xsdRefType + '\', ' + // namespace
- '\'' + priv.options.namespace + '\', ' + // backRefNS
- '\'' + rowPK + '\', ' + // backRefPK
- '\'' + columnProps.column + '\')' + // backRefField
- '" ' +
- 'href="index.php?_route=ViewTableAjax' +
- '&namespace=' + columnProps.xsdRefNsPrefix.replace('__x3A__', '/') + '/' + columnProps.xsdRefType +
- '&backRefNS=' + priv.options.namespace +
- '&backRefPK=' + rowPK +
- '&backRefField=' + columnProps.column +
- '">przeglądaj</a>')
- }
- if (columnProps.xsdType && 'xsd:base64Binary' === columnProps.xsdType) {
- cellCnt.empty();
- if (val) {
- 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>');
- } else {
- cellCnt.append('<span style="color:silver" title="Brak danych">N/S;</span>');
- }
- }
- if (i > 1 && priv.options.longDesc) {// TODO: use better check for columns: functions and pk
- cellNode.addClass('tbl-short-txt');
- if (showTooltip) {
- cellCnt.tooltip({title: cellCnt.text(), placement: 'left'});
- }
- }
- }
- return rowNode;
- };
- priv.renderCellRowFunctions = function(rowFunctions, rowPK, rowProps) {
- var cellNode = $('<td></td>');
- var keys = Object.keys(rowFunctions);
- var total = keys.length;
- var moreFuncBtnNode;
- var moreFunctions = [];
- var idx;
- if (priv.options.debug || DBG) console.log('TableAjax::renderCellRowFunctions: rowFunctions', rowFunctions);
- idx = keys.indexOf('hist');
- if (idx !== -1) {
- histFunc = keys.splice(idx, 1);
- keys.push('hist');
- }
- moreFunctions = keys.splice(3);
- keys.forEach(function(key) {
- // TODO: support for ui-function in rowFunctions
- // var funObj = rowFunctions[key];
- // var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: false});
- // DBG && console.log('TableAjax::renderCellRowFunctions: rowFunction[' + key + ']', { funObj: funObj, uiFunc: funObj['ui-function'], uiFuncExists: global[funObj['ui-function']] });
- // if (funObj['ui-function'] && global[funObj['ui-function']]) {
- // funcNode.on('click', function (event) { event.preventDefault(); global[funObj['ui-function']](rowPK); });
- // }
- var funObj = rowFunctions[key];
- var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: false});
- funcNode.appendTo(cellNode);
- });
- moreFuncBtnNode = $('<a href="#" style="margin:0 2px;text-decoration:none" title="Więcej funkcji dla rekordu nr '+rowPK+'" class="glyphicon glyphicon-menu-hamburger"> </a>');
- moreFuncBtnNode.on('click', {rowPK: rowPK, rowFunctions: rowFunctions, more: moreFunctions}, priv.popoverCellMoreFunctions);
- moreFuncBtnNode.appendTo(cellNode);
- return cellNode;
- };
- priv.popoverCellMoreFunctions = function(e) {
- e.preventDefault();
- e.stopPropagation();
- if (!e.data || !e.data.rowPK) {
- if (priv.options.debug || DBG) console.log('NO data');
- return false;
- }
- if (priv.options.debug || DBG) console.log('TableAjax::popoverCellMoreFunctions: rowPK', e.data.rowPK, 'moreFunctions', e.data.more, 'rowFunctions', e.data.rowFunctions);
- var lastId = _popoverCell.data('rowid');
- var lastCol = _popoverCell.data('col');
- var rowPK = e.data.rowPK;
- var moreFunctions = e.data.more;
- var rowFunctions = e.data.rowFunctions;
- var funcListNode;
- if (lastId == e.data.rowPK && lastCol == 'moreFunctions') {
- //_popoverCellCurrent.popover('toggle');
- return;
- }
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('destroy');
- }
- _popoverCell.data('rowid', rowPK);
- _popoverCell.data('col', 'rowFunctions');
- _popoverCell.empty();
- funcListNode = $('<ul class="list-unstyled popoverRowFunctions"></ul>').appendTo(_popoverCell);
- moreFunctions.forEach(function(funcName) {
- var funcItemNode = $('<li></li>').appendTo(funcListNode),
- funObj = rowFunctions[funcName],
- funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: true})
- ;
- funcNode.addClass('func_name-' + funcName);
- funcItemNode.append(funcNode);
- });
- _popoverCell.append('<div class="popoverCellContent" style="white-space:normal"></div>');
- _popoverCellCurrent = jQuery(e.currentTarget);
- // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">×</button>'
- var opts = {
- container: 'body',
- placement: 'right',
- trigger: 'click',
- template: '',
- html: true,
- content: _popoverCell.html()
- }
- opts.template += '<div class="popover" role="tooltip" style="max-width:600px;width:440px;">';
- {
- opts.template += '<div class="arrow"></div>';
- //opts.template += '<h3 class="popover-title"></h3>';
- opts.template += '<div style="display:block;position:relative;">';
- {
- opts.template += '<div class="popover-title">';
- opts.template += '</div>';
- opts.template += '<button type="button" class="close" onclick="return hidePopover();" style="position:absolute;right:8px;top:6px;">×</button>';
- }
- opts.template += '</div>';
- opts.template += '<div class="popover-content"></div>';
- }
- opts.template += '</div>';
- _popoverCellCurrent.popover(opts);
- _popoverCellCurrent.on('shown.bs.popover', function(e) {
- if (!_popoverCellCurrent) return;
- var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
- if (!popoverNodeId) return;
- var popover$Node = jQuery('#' + popoverNodeId);
- if (!popover$Node.length) return;
- var arrow$Node = popover$Node.children('.arrow');
- if (arrow$Node.length) {
- var posTop = parseFloat(arrow$Node.css('top'));
- arrow$Node.css('top', '' + posTop + 'px')
- }
- popover$Node.find('.popoverCellContent').html('<p class="text-muted">Pobieranie funkcji...<p>');
- priv.ajaxLoadMoreFunctionsCell(rowPK);
- });
- _popoverCellCurrent.popover('show');
- return;
- };
- priv.ajaxLoadMoreFunctionsCell = function(rowPK) {
- var dbg = (priv.options.debug || DBG);
- if (_popoverCellAjaxXhr) {
- _popoverCellAjaxXhr.abort();
- }
- _popoverCellAjaxXhr = $.ajax({
- type: 'GET',
- url: priv.options.moreFunctionsCellAjaxUrl + '&ID=' + rowPK,
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: ''
- })
- .done(function(data, textStatus, jqXHR){
- if (data && 'success' === data.type) {
- var popoverCellContent,
- rowFunctions = [],
- funcNodesToUpdate = []
- ;
- if (data.rowFunctions && data.rowFunctions.length > 0) {
- rowFunctions = data.rowFunctions;
- }
- if (!rowFunctions.length) {
- popoverCellContent = '<p class="text-muted">Brak dodatkowych funkcji</p>';
- } else if (3 === priv.options.namespace.split('/').length) { // if namesapce is AntAcl [ and has ref fields or back ref ]
- var popoverCellContent = $('<ul class="list-unstyled"></ul>');
- var rowFunctionsByType = rowFunctions.reduce(function (ret, funObj) {
- if (
- 'Powiązania od ' === funObj.label.substr(0, 'Powiązania od '.length)
- || 'Powiązania do ' === funObj.label.substr(0, 'Powiązania do '.length)
- ) {
- if (funObj.total > 0) {
- ret.refConnections.push(funObj);
- } else {
- ret.refEmptyConnections.push(funObj);
- }
- } else {
- ret.others.push(funObj);
- }
- return ret;
- // href: "https://biuro.biall-net.pl/dev-pl/se-master/index.php?_route=ViewTableAjax&namespace=default_db/BI_audit_KRS/BI_audit_KRS&childRefNS=default_db/BI_audit_KRS/BI_audit_KRS&childRefPK=2068689"
- // ico: "glyphicon glyphicon-random"
- // label: "Powiązania od 'KRS' <span class="badge">0</span>"
- // title: "Powiązania od 'Audyt / KRS' (0)"
- }, { refConnections: [], refEmptyConnections: [], others: [] });
- rowFunctionsByType.others.forEach(function(funObj) {
- var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: true});
- if (funObj.id) {
- funcNodesToUpdate.push({id: funObj.id, node: funcNode});
- } else {
- var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
- funcItemNode.append(funcNode);
- }
- });
- if (!rowFunctionsByType.refConnections.length) {
- $('<li>Brak powiązań</li>').appendTo(popoverCellContent);
- } else {
- var refConnItemNode = $('<li style="margin-top:10px"><i class="glyphicon glyphicon-random"></i> <b>Powiązania</b></li>').appendTo(popoverCellContent);
- {
- var funObj = {
- // ico: 'glyphicon glyphicon-random',
- label: 'przeglądaj',
- title: "Przeglądaj powiązania",
- href: 'index.php?_route=RefGraph&namespace=' + priv.options.namespace + '&primaryKey=' + rowPK,
- // onclick: function (e) { // TODO: open in
- // console.log('TODO: przeglądaj powiązania')
- // }
- }
- var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, { ico: true, label: true })
- refConnItemNode.append(" - ");
- refConnItemNode.append(funcNode);
- }
- var refConnFuncList = $('<ul class="list-unstyled" style="margin-left:20px"></ul>').appendTo(refConnItemNode);
- rowFunctionsByType.refConnections.forEach(function(funObj) {
- var refFunObj = Object.assign({}, funObj, {
- // ico: null,
- label: funObj.label.substr('Powiązania '.length),
- });
- var funcNode = p5UI_TableAjax_generateFunctionNode(refFunObj, rowPK, {ico: true, label: true});
- var funcItemNode = $('<li></li>').appendTo(refConnFuncList);
- funcItemNode.append(funcNode);
- })
- }
- if (rowFunctionsByType.refEmptyConnections.length) {
- var refConnItemNode = $('<li style="margin-top:10px; opacity:0.7"></li>').appendTo(popoverCellContent);
- var emptyRefsDetailsNode = $('<details></details>').appendTo(refConnItemNode);
- // $('<summary><i class="glyphicon glyphicon-random"></i> Pozostałe powiązania</summary>').appendTo(emptyRefsDetailsNode);
- $('<summary style="cursor:pointer">Pozostałe powiązania ...</summary>').appendTo(emptyRefsDetailsNode);
- var refConnFuncList = $('<ul class="list-unstyled" style="margin-left:20px"></ul>').appendTo(emptyRefsDetailsNode);
- rowFunctionsByType.refEmptyConnections.forEach(function (funObj) {
- var refFunObj = Object.assign({}, funObj, {
- // ico: null,
- label: funObj.label.substr('Powiązania '.length),
- });
- var funcNode = p5UI_TableAjax_generateFunctionNode(refFunObj, rowPK, { ico: true, label: true });
- var funcItemNode = $('<li></li>').appendTo(refConnFuncList);
- funcItemNode.append(funcNode);
- })
- }
- } else {
- var popoverCellContent = $('<ul class="list-unstyled"></ul>');
- rowFunctions.forEach(function(funObj) {
- var funcNode = p5UI_TableAjax_generateFunctionNode(funObj, rowPK, {ico: true, label: true});
- if (funObj.id) {
- funcNodesToUpdate.push({id: funObj.id, node: funcNode});
- } else {
- var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
- funcItemNode.append(funcNode);
- }
- });
- }
- //_popoverCell.append(popoverCellContent);// cache
- if (_popoverCellCurrent) {
- var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
- if (popoverNodeId) {
- var popoverNode = jQuery('#' + popoverNodeId),
- popoverCntNode = popoverNode.find('.popoverCellContent'),
- popoverRowFuncNode = popoverNode.find('.popoverRowFunctions');
- ;
- {// fix generated row Functions by loaded from ajax call
- if(dbg) console.log('popoverRowFunctions. popoverRowFuncNode', popoverRowFuncNode);
- if(dbg) console.log('popoverRowFunctions. funcNodesToUpdate', funcNodesToUpdate);
- funcNodesToUpdate.forEach(function(funcNodeInfo) {
- var className = 'func_name-' + funcNodeInfo.id,
- foundRowFuncNode = null
- ;
- if(dbg) console.log('popoverRowFunctions. funcNodesToUpdate loop:', funcNodeInfo);
- popoverRowFuncNode.find('li > a').each(function(ind, n) {
- var n$ = $(n);
- if(dbg) console.log('popoverRowFunctions loop(',ind,'):', n, 'data(func_name)', n$.data('func_name'), 'data', n$.data());
- if (n$.hasClass(className)) {
- foundRowFuncNode = n$;
- }
- });
- if (foundRowFuncNode) {
- foundRowFuncNode.replaceWith(funcNodeInfo.node);
- } else {
- var funcItemNode = $('<li></li>').appendTo(popoverCellContent);
- funcItemNode.append(foundRowFuncNode);
- }
- });
- }
- popoverCntNode.empty().append(popoverCellContent);
- if (rowFunctions.length <= 0) {
- popoverCntNode.find('p.text-muted').delay(600).hide(300);
- }
- }
- }
- }
- });
- };
- priv.renderRowEmptyNode = function() {
- var rowNode = $('<tr></tr>');
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- $('<td class="text-right stickyCol stickyCol1"> </td>').appendTo(rowNode);
- }
- if (_state.primaryKey && priv.options.checkboxes) {
- var cellNode = $('<td class="stickyCol stickyCol2" style="padding:3px 5px"></td>').appendTo(rowNode);
- }
- for (var i = 0; i < _state.colsSorted.length; i++) {
- var columnName = _state.colsSorted[i],
- columnProps = _data.cols[columnName]
- ;
- if (!columnProps) return;
- if (columnProps.hidden) continue;// "unique" is hidden - TODO: rm "unique" from _state.colsSorted ?
- if (i == 1) {// TODO: 1 is pk - use better check
- $('<td class="stickyCol3"> </td>').appendTo(rowNode);
- } else {
- $('<td> </td>').appendTo(rowNode);
- }
- }
- return rowNode;
- };
- priv.renderTableTheadSort = function () { // _uiNodeTheadSortRow
- DBG && console.log('DBG:renderTableTheadSort', { '_state._currSortCol': _state._currSortCol, '_state._currSortFlip': _state._currSortFlip });
- ReactDOM.render(
- h(p5UI__TableAjaxTheadSortRow, {
- namespace: priv.options.namespace,
- tblFunctions: priv.options.tblFunctions,
- filtersClean: priv.options.filtersClean,
- priv: priv,
- primaryKey: _state.primaryKey,
- checkboxes: priv.options.checkboxes,
- selectedStore: priv.options.selectedStore,
- selectedActions: priv.options.selectedActions,
- colsSorted: _state.colsSorted,
- _data_cols: _data.cols,
- filterStore: priv.options.filterStore,
- filterActions: priv.options.filterActions,
- // checkboxIdContext: priv.options.checkboxIdContext,
- }),
- _uiNodeTheadSortRow
- );
- };
- priv.renderHeadSpecialFilters = function() {
- DBG && console.warn('DBG:priv.renderHeadSpecialFilters...', { 'priv.options.specialFilterFunctions': priv.options.specialFilterFunctions });
- if (!priv.options.specialFilterFunctions) {
- return;
- }
- ReactDOM.render(
- h(P5UI__TableAjaxSpecialFilters, {
- store: priv.options.filterStore,
- actions: priv.options.filterActions,
- specialFilters: priv.options.specialFilterFunctions,
- namespace: priv.options.namespace,
- }),
- _uiNodeSpecialFilters
- );
- };
- priv.renderTableTheadFilter = function () { // _uiNodeTheadFiltersRow
- DBG && console.log('DBG::renderTableTheadFilter...'); // exec once, at init
- ReactDOM.render(
- h(p5UI__TableAjaxTheadFiltersRow, {
- namespace: priv.options.namespace,
- filterStore: priv.options.filterStore,
- filterActions: priv.options.filterActions,
- checkboxes: priv.options.checkboxes,
- primaryKey: _state.primaryKey,
- colsSorted: _state.colsSorted,
- _data_cols: _data.cols,
- rowFunctions: priv.options.rowFunctions,
- filtersClean: priv.options.filtersClean,
- forceFilterInit: priv.options.forceFilterInit,
- checkboxIdContext: priv.options.checkboxIdContext,
- }),
- _uiNodeTheadFiltersRow
- );
- };
- priv.renderTableTfoot = function() {
- _uiNode$Table.find('tfoot').remove();
- _foot = $('<tfoot></tfoot>').insertAfter(_bodyNode);
- //$(_uiMainContainerNode).next('.foot').replaceWith(_foot);
- };
- priv.renderFooter = function() {
- priv.renderFooterInfo();
- priv.renderFooterPagination();
- priv.renderFooterPageSizes();
- priv.renderFooterColumnPicker();
- priv.renderFooterFunctions();
- priv.renderFooterExport();
- };
- priv.renderFooterInfo = function() {
- DBG && console.log('DBG:TableAjax::renderFooterInfo', { _uiNodeFooterInfo: _uiNodeFooterInfo });
- var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
- var total = _data.total;
- var renderedRowsCount = Math.min(_data.rows.length, _state.pageSize);
- var toRow = fromRow + renderedRowsCount;
- var outTotal = (_state.isLoadingTotal) ? '...' : total;
- DBG && console.log('DBG:TableAjax::renderFooterInfo', { total: total,
- asyncFetchTotal__lastSentReqId: _state.asyncFetchTotal__lastSentReqId,
- asyncFetchTotal__lastReceivedId: _state.asyncFetchTotal__lastReceivedId,
- isLoadingTotal: _state.isLoadingTotal
- });
- if (_state.isLoadingTotal) {
- outTotal = '...';
- _uiNodeFooterInfo.innerHTML = '<div style="font-size:12px; line-height:1.4em;">' +
- '<strong>Łącznie wyników:</strong> <span class="hide-on-loading">' + outTotal + '</span>' +
- '<br>' +
- ( (toRow > 0)
- ? '<small class="hide-on-loading" style="color:#999; font-size:10px">' + p5Utils__format('Wyświetlane wiersze: od {0} do {1}', [fromRow + 1, toRow]) + '</small>'
- : ''
- ) +
- '</div>';
- } else if (total > 0) {
- outTotal = total;
- _uiNodeFooterInfo.innerHTML = '<div style="font-size:12px; line-height:1.4em;">' +
- '<strong>Łącznie wyników:</strong> <span class="hide-on-loading">' + outTotal + '</span>' +
- '<br>' +
- '<small class="hide-on-loading" style="color:#999; font-size:10px">' + p5Utils__format('Wyświetlane wiersze: od {0} do {1}', [fromRow + 1, toRow]) + '</small>' +
- '</div>';
- } else {
- _uiNodeFooterInfo.innerHTML = '<p><strong>Brak wierszy pasujących do kryteriów wyszukiwania<strong></p>';
- }
- };
- priv.renderFooterPagination = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
- currentNode = $(_uiMainContainerNode).next('.foot').find('.' + nodeClass),
- node;
- var currPage = _state.page;
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
- if (_state.isLoadingTotal || _data.total > 0) {
- var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
- var renderedRowsCount = Math.min(_data.rows.length, _state.pageSize);
- var toRow = fromRow + renderedRowsCount;
- var total = (_data.total > 0) ? _data.total : toRow;
- node = $('<div class="btn-group ' + nodeClass + '"></div>');
- var totalPages = Math.ceil(total / _state.pageSize);
- var lowerPage = currPage - 2;
- var upperPage = currPage + 2;
- if (upperPage > totalPages) {
- var diff = upperPage - totalPages;
- upperPage = totalPages;
- lowerPage -= diff;
- }
- if (lowerPage < 1) lowerPage = 1;
- if (upperPage < 5) upperPage = 5;
- var enableNextPageLink = (
- (_state.isLoadingTotal && renderedRowsCount === _state.pageSize)
- || (!(_state.isLoadingTotal) && currPage < totalPages)
- );
- var enableLastPageLink = ( !(_state.isLoadingTotal) && (currPage < totalPages) );
- //$(p5Utils__format('<li class="{0}"><a href="#"><<</a></li>', [currPage == 1 ? 'disabled' : '']))
- $(p5Utils__format('<button type="button" class="btn btn-default{0}"><<</button>', [currPage == 1 ? ' disabled' : '']))
- .on('click', {pageIndex: 1}, priv.pageChanged)
- .appendTo(node);
- //$(p5Utils__format('<li class="{0}"><a href="#"><</a></li>', [currPage == 1 ? 'disabled' : '']))
- $(p5Utils__format('<button type="button" class="btn btn-default{0}"><</button>', [currPage == 1 ? ' disabled' : '']))
- .on('click', {pageIndex: currPage - 1}, priv.pageChanged)
- .appendTo(node);
- for (var i = lowerPage; i <= upperPage; i++) {
- var link;
- //if (i != currPage) link = $(p5Utils__format('<li class="{1}"><a href="#">{0}</a></li>', [i, i > totalPages ? 'disabled' : '']));
- if (i != currPage) link = $(p5Utils__format('<button type="button" class="btn btn-default{1}">{0}</button>', [i, i > totalPages ? ' disabled' : '']));
- //if (i == currPage) link = $(p5Utils__format('<li class="active"><a href="#">{0}</a></li>', [i]));
- if (i == currPage) link = $(p5Utils__format('<button type="button" class="btn btn-default active">{0}</button>', [i]));
- if (link) {
- link.on('click', {pageIndex: i}, priv.pageChanged);
- link.appendTo(node);
- }
- }
- //$(p5Utils__format('<li class="{0}"><a href="#">></a></li>', [currPage == totalPages ? 'disabled' : '']))
- $(p5Utils__format('<button type="button" class="btn btn-default{0}">></button>', [enableNextPageLink ? '' : ' disabled']))
- .on('click', {pageIndex: currPage + 1}, priv.pageChanged)
- .appendTo(node);
- //$(p5Utils__format('<li class="{0}"><a href="#">>></a></li>', [currPage == totalPages ? 'disabled' : '']))
- $(p5Utils__format('<button type="button" class="btn btn-default{0}">>></button>', [enableLastPageLink ? '' : ' disabled']))
- .on('click', {pageIndex: totalPages}, priv.pageChanged)
- .appendTo(node);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterPageSizes = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__pagesizes',
- currentNode = $(_uiMainContainerNode).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
- if (priv.options.pageSizes.length > 0) {
- node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
- var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Liczba wierszy </button>').appendTo(node);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
- $.each(priv.options.pageSizes, function(index, val) {
- var li = $('<li></li>').appendTo(ul);
- if (val == priv.options.pageSize) {
- $(p5Utils__format('<a style="color:#337AB7;">{0}</a>', [val])).appendTo(li);
- } else {
- $(p5Utils__format('<a href="#">{0}</a>', [val])).appendTo(li);
- }
- });
- node.on('click', 'a', priv.pageSizeChanged);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterColumnPicker = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
- currentNode = $(_uiMainContainerNode).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
- if (priv.options.columnPicker) {
- node = $('<div class="btn-group dropup columnpicker ' + nodeClass + '"></div>');
- var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Kolumny </button>').appendTo(node);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu" style="max-height:250px;overflow:auto;">').appendTo(node);
- var selectedFilter = priv.modelColFilter_getSelected();
- priv.modelColFilter_getFilters().map(function(colFltr) {
- var li = $('<li></li>').appendTo(ul),
- selected = (selectedFilter && selectedFilter == colFltr.name)? 'checked="checked"' : '',
- input = '<input ' + selected + ' type="radio" style="margin:0"/>',
- a = $('<a href="#" data-col_filter="' + colFltr.name + '" style="padding:0px 20px;">' + input + ' ' + colFltr.label + '</a>').appendTo(li);
- if ('all' != colFltr.name && 'most_used' != colFltr.name) {
- arm = $('<button data-col_filter="' + colFltr.name + '" class="pull-right btn btn-xs btn-link" style="margin:0;padding:0;border:0;color:red">' + '×' + '</a>').appendTo(a);
- arm.on('click', priv.modelColFilter_onClickRemoveFilter)
- }
- });
- {// if (!selectedFilter) {// save current filter
- var li = $('<li style="text-align:center; clear:both"></li>').appendTo(ul)
- priv.modelColFilter_getSaveBtn().appendTo(li);
- }
- $('<li class="divider"></li>').appendTo(ul);
- $.each(_data.cols, function(col, props) {
- if (props.type != "unique" && col != _state.primaryKey) {
- var li = $('<li></li>').appendTo(ul),
- label = (props.friendly || col).replace(/<br\/?>/g, ' '),
- input = p5Utils__format('<input {0} type="checkbox" title="{1}" value="{1}" style="margin:0"/> {2}', [(props.hidden) ? '' : 'checked', col, label]),
- a = $('<a href="#" style="padding:0px 20px;">' + input + '</a>').appendTo(li);
- }
- });
- node.on('click', 'input[type="checkbox"]', priv.columnPickerClicked);
- node.on('click', 'a', priv.columnPickerLinkClicked);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterFunctions = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__functions',
- currentNode = $(_uiMainContainerNode).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
- if (priv.options.tblFunctions) {
- node = $('<div class="btn-group ' + nodeClass + '"></div>');
- $.map(priv.options.tblFunctions, function(funObj, funName){
- var funHtml = $('<button class="btn btn-sm btn-default"></button>');
- if (funObj.title) funHtml.attr('title', funObj.title);
- if (funObj.method) funHtml.on('click', priv[funObj.method]);
- else if (funObj.href) funHtml.on('click', {hash:funObj.href}, priv.routeChanged);
- var funIconHtml = $('<i></i>');
- if (funObj.icon) funIconHtml.attr('class', 'glyphicon glyphicon-' + funObj.icon);
- funIconHtml.prependTo(funHtml);
- funHtml.addClass('btn');
- funHtml.appendTo(node);
- });
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterExport = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__export',
- currentNode = $(_uiMainContainerNode).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
- if (priv.options.exportFields && priv.options.exportFields.length) {
- node = $('<div class="btn-group dropup pagesize ' + nodeClass + '"></div>');
- var btn = $('<button class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown" href="#">Export </button>').appendTo(node);
- var span = $('<span class="caret"></span>').appendTo(btn);
- var ul = $('<ul class="dropdown-menu" style="max-height:250px;padding:5px 20px 5px 8px;overflow:auto;">').appendTo(node);
- $.each(_data.cols, function(col, props) {
- if (-1 !== priv.options.exportFields.indexOf(col)) {
- var li = $('<li></li>').appendTo(ul);
- $(p5Utils__format('<input {0} type="checkbox" title="{1}" value="{1}" > {2}</input>', [(_exportFieldsSelect[col])? 'checked' : '', col, props.friendly || col])).appendTo(li);
- li.on('click', 'input', priv.exportFieldChanged);
- }
- });
- var li;
- li = $('<li></li>').appendTo(ul);
- $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Podgląd <em style="font-size:85%">(HTML)</em></a>').appendTo(li);
- li.on('click', 'a', priv.exportToHTML);
- li = $('<li></li>').appendTo(ul);
- $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do CSV</a>').appendTo(li);
- li.on('click', 'a', priv.exportToCSV);
- li = $('<li></li>').appendTo(ul);
- $('<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);
- li.on('click', 'a', priv.exportToCSVWinCP1250);
- li = $('<li></li>').appendTo(ul);
- $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export XLS"></i>Export do XLS</a>').appendTo(li);
- li.on('click', 'a', priv.exportToXLS);
- li = $('<li></li>').appendTo(ul);
- $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share" title="Export XLSX"></i>Export do XLSX</a>').appendTo(li);
- li.on('click', 'a', priv.exportToXLSX);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderInlineEditBox = function() {
- var nodeClass = 'tblAjax__' + 'inlineEditBox',
- currentNode = $(_uiMainContainerNode).parent().children('.' + nodeClass),
- node;
- var node = $('<div class="' + nodeClass + ' modal fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>');
- var modalWrap = $('<div class="modal-dialog"></div>').appendTo(node);
- var modalWrap = $('<div class="modal-content"></div>').appendTo(modalWrap);
- var frmInlineEdit = $('<form style="margin:0;padding:0;"></form>').appendTo(modalWrap);
- var iebHead = $('<div class="modal-header" style="cursor:pointer">').appendTo(frmInlineEdit);
- $('<button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="glyphicon glyphicon-remove" style="color:red"></i></button>').appendTo(iebHead);
- $('<h4 id="myModalLabel">Edytuj</h4>').appendTo(iebHead);
- var iebBodyWrap = $('<div class="modal-body" style="padding:0"></div>').appendTo(frmInlineEdit);
- var iebBody = $('<div style="padding:15px"></div>').appendTo(iebBodyWrap);
- $('<input type="hidden" name="ID" value="">').appendTo(iebBody);
- $('<input type="hidden" name="col" value="">').appendTo(iebBody);
- $('<div class="inlineEditBox-cnt"></div>').appendTo(iebBody);
- var iebFoot = $('<div class="modal-footer"></div>').appendTo(frmInlineEdit);
- $('<button class="btn btn-close" data-dismiss="modal" aria-hidden="true">Zamknij</button>').appendTo(iebFoot);
- var iebBtnSave = $('<input type="submit" value="Zapisz" class="btn btn-primary btn-save">').appendTo(iebFoot);
- frmInlineEdit.on('submit', function() {
- var inlineEditBox$Node = $(_uiMainContainerNode).parent().children('.tblAjax__inlineEditBox');
- var data = inlineEditBox$Node.find('form').serialize();
- inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'Dane poprawnie zaktualizowane';
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- $.ajax({
- data: data,
- dataType: 'json',
- type: "POST",
- url: priv.options.editInlineSaveUrl
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- publ.refresh();
- inlineEditBox$Node.modal('hide');
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- inlineEditBox$Node.modal('hide');
- });
- return false;
- });
- currentNode.replaceWith(node);
- };
- priv.exportFieldChanged = function(e) {
- e.stopPropagation();
- var column = $(this).val();
- _exportFieldsSelect[column] = !_exportFieldsSelect[column];
- };
- priv.exportToHTML = function(e) {
- priv.exportData('html', $(this), e);
- };
- priv.exportToCSV = function(e) {
- priv.exportData('csv', $(this), e);
- };
- priv.exportToCSVWinCP1250 = function(e) {
- priv.exportData('csv_cp1250', $(this), e);
- };
- priv.exportToXLS = function(e) {
- priv.exportData('xls', $(this), e);
- };
- priv.exportToXLSX = function(e) {
- priv.exportData('xlsx', $(this), e);
- };
- priv.exportData = function(format, node, e) {
- var exportFields = [];
- $.each(_exportFieldsSelect, function(col, selected) {
- if (selected) {
- exportFields.push(col);
- }
- });
- if (!exportFields.length) {
- alert('Nie wybrano żadnych pól do eksportu.');
- e.preventDefault();
- return false;
- }
- var limit = 10000;
- if (!_data.total || _data.total <= 0) {
- alert('Brak rekordów do eksportu.');
- e.preventDefault();
- return false;
- }
- if (_data.total > limit) {
- if (!confirm('Za dużo rekordów. Wyeksportowane zostaną tylko pierwsze ' + limit + ' z ' + _data.total + ' rekordów.')) {
- e.preventDefault();
- return false;
- }
- }
- e.preventDefault();
- var frm = document.createElement('form');
- frm.style.display = "none";
- frm.setAttribute('target', "_blank");
- frm.method = "POST";
- frm.action = "index.php?_route=ExportTableAjax&" + priv.filter_getFilterQuery();
- function craeteHtmlInputElement(name, value) {
- var input = document.createElement("input");
- input.value = value;
- input.name = name;
- return input;
- }
- frm.appendChild(craeteHtmlInputElement('namespace', priv.options.namespace));
- frm.appendChild(craeteHtmlInputElement('format', format));
- frm.appendChild(craeteHtmlInputElement('flds', exportFields.join(',')));
- frm.appendChild(craeteHtmlInputElement('sortCol', (_state._currSortCol || '')));
- frm.appendChild(craeteHtmlInputElement('sortDir', (_state._currSortFlip ? "desc" : "asc")));
- var url = new URL(window.location.href);
- if (url.searchParams.get('childRefNS')) {
- frm.appendChild(craeteHtmlInputElement('childRefNS', url.searchParams.get('childRefNS')));
- frm.appendChild(craeteHtmlInputElement('childRefPK', url.searchParams.get('childRefPK')));
- }
- if (url.searchParams.get('backRefNS')) {
- frm.appendChild(craeteHtmlInputElement('backRefNS', url.searchParams.get('backRefNS')));
- frm.appendChild(craeteHtmlInputElement('backRefPK', url.searchParams.get('backRefPK')));
- frm.appendChild(craeteHtmlInputElement('backRefField', url.searchParams.get('backRefField')));
- }
- document.body.appendChild(frm);
- frm.submit();
- document.body.removeChild(frm);
- };
- priv.showFailFetchDataMsg = function () {
- var clearAllFiltersBtn = jQuery('<button class="btn btn-xs btn-link" style="color:red">usunąć wszystkie filtry</button>')
- clearAllFiltersBtn.on('click', function () {
- priv.options.filterStore.dispatch( priv.options.filterActions.clearAllFilters() )
- jQuery(this).parent().remove();
- })
- var msgNode = jQuery('<div class="alert alert-danger" style="clear:both; max-width:600px; margin: 10px auto">' +
- 'Wystąpił błąd podczas pobierania danych ' +
- '<a href="javascript:window.location.reload()" class="btn btn-xs btn-link">spróbuj ponownie</a>.' + '<br>' +
- 'Jeśli problem się powtarza, spróbuj ' +
- '</div>')
- msgNode.append(clearAllFiltersBtn);
- jQuery(_uiMainContainerNode).prepend(msgNode);
- }
- /*
- calls the webservice(if defined).
- used only inside priv.init
- */
- priv.update = function(callback) {
- var skipCols, resetChecked;// undefined
- if (!priv.options.url) {
- if (priv.options.debug || DBG) console.log('no url found');
- return;
- }
- if (priv.options.debug || DBG) console.log(p5Utils__format('requesting data from url:{0}', [priv.options.url]));
- var initUrlAdd = '&' + priv.filter_getFullFilterQuery();
- if (SKIP_TOTAL) initUrlAdd += '&' + 'SKIP_TOTAL=1';
- DBG && console.warn('DBG:update... - FETCH_DATA', { initUrlAdd, '_state._filterQuery': _state._filterQuery, '_state._specialFilterQuery': _state._specialFilterQuery, _state });
- // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych (init) ...'});
- window.fetch(priv.options.url + initUrlAdd, {
- method: priv.options.urlPost ? 'POST' : 'GET',
- credentials: 'same-origin',// add cookies
- }).then(function (response) {
- return response.json()
- }).then(function (data) {
- if (priv.options.debug || DBG) console.log('loadDataAjax:fetch:update: request finished response data:', data);
- if ('success' == data.type) {
- return data;
- } else {
- p5UI__notifyAjaxCallback(data);
- priv.showFailFetchDataMsg();
- }
- return null;
- }).then(function (data) {
- if (priv.options.debug || DBG) console.log('loadDataAjax:fetch:update: request finished data:', data);
- if (!data) return;
- if (data && data.cols) {
- priv.setStateCols(data.cols, data.primaryKey);
- }
- // assign the new state (data)
- state = {data: {}};
- if (!skipCols) state.data.cols = data.cols || {};
- state.data.rows = data.rows || [];
- state.data.total = data.total || 0;
- state.data.primaryKey = data.primaryKey || 'ID';
- state.page = data.page || 0;
- state.pageSize = data.pageSize || priv.options.pageSize;
- state.filters = data.filters || {};
- DBG && console.warn('DBG:update... - FETCH_DATA END priv.setState(state);', { state });
- if (SKIP_TOTAL) _state.isLoadingTotal = true;
- priv.setState(state);
- if (SKIP_TOTAL) priv.asyncFetchTotal((priv.options.url + initUrlAdd).replace('SKIP_TOTAL=1', 'ONLY_TOTAL=1'))
- if (typeof callback == "function") {
- callback.call(this);
- }
- }).catch(function (e) {
- console.log('loadDataAjax:fetch: ERR:', e);
- });
- };
- /*
- assigns the new data.
- */
- priv.setState = function(state) {
- var oldState = _state; // TODO: use to check what really changed (use extend!)
- var renderParts = {};
- if (state.data) {
- if (state.data.cols && Object.keys(state.data.cols).length > 0) {
- priv.setStateCols(state.data.cols, state.data.primaryKey);
- priv.setStateData(state.data);
- } else {
- priv.setStateData(state.data);
- }
- renderParts['body'] = true;
- renderParts['foot_pagination'] = true;
- }
- if (state.hasOwnProperty('specialFilters')) {
- _state.specialFilters = state.specialFilters;
- renderParts['head__specialFilters'] = true;
- }
- if (state.hasOwnProperty('page')) {
- if (state.page != _state.page) {
- _state.page = state.page;
- renderParts['foot_pagination'] = true;
- }
- }
- if (state.hasOwnProperty('pageSize')) {
- if (state.pageSize != _state.pageSize) {
- _state.pageSize = state.pageSize;
- renderParts['foot_pagination'] = true;
- }
- }
- if (state.hasOwnProperty('filters')) {
- renderParts['head__specialFilters'] = true;
- renderParts['foot_pagination'] = true;
- }
- renderParts = Object.keys(renderParts);
- if (renderParts.length > 0) {
- DBG && console.log('DBG::trigger(TableAjax:render): ', renderParts);
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', renderParts);
- }
- };
- priv.setStateCols = function(cols, primaryKey) {
- if (priv.options.debug || DBG) console.log('priv.setStateCols: ', {primaryKey: primaryKey, cols: cols});
- // console.log("priv.setStateCols");
- // console.trace();
- _state.cols = cols;
- _state.primaryKey = primaryKey || _state.primaryKey;
- // fix col name - props.column
- $.each(_state.cols, function(col, props) {
- props.column = col;
- });
- // fix col types - default 'string'
- $.each(_state.cols, function(col, props) {
- if (!props.type) cols[col].type = "string";
- });
- // fix props.filter - set true if not set - TODO: allow filter this col?
- $.each(_state.cols, function(col, props) {
- if (props.filter == undefined) props.filter = true;
- });
- if (_state.primaryKey) {
- //create a unique column definition
- _state.cols["unique"] = {
- column: "unique",
- type: "unique",
- index: -1,
- hidden: true
- };
- }
- _state.colsSorted = Object.keys(_state.cols).sort(function(a, b) {
- return _state.cols[a].index - _state.cols[b].index;
- });
- };
- priv.setStateData = function(pData) {
- var listPrimaryKeys = (pData && pData.rows && pData.rows.length)
- ? pData.rows.map(function (item) {
- return item['@primaryKey'];
- })
- : []
- ;
- jQuery(_uiMainContainerNode).trigger('TableAjax:updateRows', { primaryKeys: listPrimaryKeys });
- if (priv.options.checkboxes) {
- priv.options.selectedStore.dispatch( priv.options.selectedActions.setPrimaryKeys(priv.options.namespace, listPrimaryKeys) );
- }
- var data = $.extend(true, {}, pData);
- data.cols = _state.cols;// always use old cols - change cols mved to priv.setStateCols
- _data = data;
- _data.rowsOrg = _data.rows;
- };
- /*
- helper that returns the underlying data by the unique value
- */
- priv.getRow = function(uniqueValue) {
- var row;
- $.each(_data.rowsOrg, function(i, r) {
- if (r[_state.primaryKey] == uniqueValue) {
- row = r;
- return false;
- }
- });
- return row;
- };
- priv.longTextChanged = function(e) {
- priv.options.longDesc = !priv.options.longDesc;
- _bodyNode.find('td').each(function(ind, el){
- var $el = jQuery(el);
- if (!$el.attr('class') || $el.attr('class') == 'tbl-short-txt') {
- if (el.firstChild && el.firstChild.nodeName == 'SPAN') {
- if (priv.options.longDesc) {
- $el.addClass('tbl-short-txt');
- var $elSpan = jQuery(el.firstChild);
- $elSpan.tooltip({title: $elSpan.text(), placement: 'left'});
- } else {
- $el.removeClass('tbl-short-txt');
- }
- }
- }
- });
- return false;
- };
- priv.mapEditorHide = function() {
- priv.options.mapEditor = false;
- if ('window' == priv.options.mapEditorContainer) {
- //_mapEditorDialog.dialog("close");
- _mapEditorDialog.dialog("destroy");
- }
- _mapEditorWrap.hide();
- _mapEditor.hide();
- };
- priv.mapEditorShow = function() {
- //console.log('TODO:mapEditorShow():', priv.options.mapEditorContainer, 'visible:', priv.options.mapEditor);
- priv.options.mapEditor = true;
- _mapEditor.show();
- _mapEditorWrap.show();
- _mapEditor.TableAjaxMap({
- //debug: true,
- wpsUrl: 'http://biuro.biall-net.pl/wps',
- wfsUrl: 'http://biuro.biall-net.pl/wps',
- showAddLayerWidget: (priv.options.hasAdditionalLayers) ? true : false,
- zoomStrategyActivate: 14,
- layerName: priv.options.labelHtml,
- addBtn: {
- title: 'Przenieś mapę do okna',
- displayClass: 'mapEditor-btnBackToWindow',
- trigger: function() {
- priv.mapEditorHide();
- priv.options.mapEditorContainer = 'window';
- priv.mapEditorShow();
- priv.resizableMapDockNode('destroy');
- }
- },
- onSaveFeature: function(selectedRecordId, selectedFeatureExtent) {
- if (priv.options.debug || DBG) console.log('onSaveFeature (',selectedRecordId,'/',selectedFeatureExtent,') ', this);
- if (!selectedRecordId) {
- alert('Brak zaznaczonego rekordu - wybierz rekord z tabeli');
- return;
- }
- function notifyAjaxCallback(data) {
- var notify = {};
- notify.type = (data && data.type)? data.type : '';
- notify.msg = (data && data.msg)? data.msg : '';
- switch (notify.type) {
- case 'success':
- if (!notify.msg) notify.msg = 'Aktualizacja danych dla rekordu ' + selectedRecordId;
- break;
- case 'info':
- if (!notify.msg) notify.msg = 'Nie wprowadzono żadnych zmian';
- break;
- case 'error':
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- case 'warning':
- notify.type = 'warn';
- if (!notify.msg) notify.msg = 'Wystąpiły błędy';
- break;
- default:
- notify.msg = 'Nieznany błąd';
- if (data && data.errorCode) notify.msg += ' ' + data.errorCode;
- notify.type = '';
- }
- jQuery.notify(notify.msg, notify.type);
- }
- $.ajax({
- data: {polygon: selectedFeatureExtent},
- dataType: 'json',
- type: "POST",
- url: priv.options.theGeomSaveUrl + '&ID=' + selectedRecordId
- })
- .done(function(data, textStatus, jqXHR){
- notifyAjaxCallback(data);
- //jQuery.notify('Aktualizacja danych dla rekordu ' + selectedRecordId, 'success');
- publ.loadPage(0);// TODO: reload table data
- })
- .fail(function(jqXHR){// jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});
- if (jqXHR.responseJSON) {
- notifyAjaxCallback(jqXHR.responseJSON);
- }
- else {
- var txt = jqXHR.responseText || 'Wystąpiły błędy';
- if (jqXHR.status == 404) {
- jQuery.notify(jqXHR.responseText, 'error');
- } else {
- jQuery.notify(jqXHR.responseText, 'warn');
- }
- }
- });
- },
- onSelectBox: function(bounds) {
- if (undefined !== OpenLayers.Bounds && bounds instanceof OpenLayers.Bounds) {
- var column = 'the_geom';
- var filter = 'BBOX:' + bounds.top + ',' + bounds.right + ',' + bounds.bottom + ',' + bounds.left;
- priv.options.filterStore.dispatch( priv.options.filterActions.setFilter(column, filter) )
- }
- }
- });
- priv.mapEditorShowElement();
- };
- priv.mapEditorShowElement = function() {
- if ('window' == priv.options.mapEditorContainer) {
- var mapEditor = _mapEditorWrap.children('.mapEditor-map');
- if (!mapEditor || !mapEditor.length) {
- var tblCont = jQuery(_uiMainContainerNode).parent('.AjaxTableCont');
- var mapEditor = tblCont.children('.AjaxTableCont-mapEditorContainer').children('.mapEditor-map');
- if (!mapEditor || !mapEditor.length) {
- // TODO: create new map
- }
- _mapEditorWrap.append(mapEditor);
- }
- _mapEditorWrap.css({padding:'5px'});
- _mapEditorDialog = _mapEditorWrap.dialog({
- width: 540,
- minWidth: 400,
- minHeight: 400,
- open: function(e, ui) {
- var n = jQuery(this),
- mapWrap = n.children(":first"),
- map = mapWrap.children(":first");
- map.css({width: n.width() - 5, height: n.height() - 5});
- _mapEditor.TableAjaxMapUpdateSize();
- },
- resizeStart: function(e, ui) {
- jQuery(this).children(":first").children(":first").css({display:'none'});
- },
- resizeStop: function(e, ui){
- var n = jQuery(this),
- map = n.children(":first").children(":first");
- n.css({width: n.parent().width()});
- map.css({display: 'block', height: n.height(), width: n.width()});
- _mapEditor.TableAjaxMapUpdateSize();
- },
- dragStop: function(e, ui){
- _mapEditor.TableAjaxMapUpdateSize();// to prevent drag-zoom error
- }
- });
- _mapEditorWrap.bind('dialogclose', function(e) {
- priv.options.mapEditor = false;
- });
- var dialogTitleBar = _mapEditorDialog.parent().parent().find('.ui-dialog-titlebar');
- var dialogTitleBarCloseBtn = dialogTitleBar.find('.ui-dialog-titlebar-close');
- if (dialogTitleBarCloseBtn) {
- 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>');
- btnToggle.on('click', function(e) {
- priv.options.mapEditorContainer = 'dock';
- _mapEditorWrap.dialog('close');
- priv.mapEditorShowElement();
- });
- btnToggle.insertBefore(dialogTitleBarCloseBtn);
- }
- }
- else if ('dock' == priv.options.mapEditorContainer) {
- priv.resizableMapDockNode('prepare');
- _mapEditor.TableAjaxMapUpdateSize();
- }
- };
- priv.resizableMapDockNode = function(task) {
- if ('prepare' == task) {
- var mapEditor = _mapEditorWrap.children('.mapEditor-map');
- if (mapEditor && mapEditor.length) {// map is inside _mapEditorWrap (window)
- var mapDockNode = jQuery('<div class="AjaxTableCont-mapEditorContainer"></div>');
- var tblCont = jQuery(_uiMainContainerNode).parent('.AjaxTableCont');
- tblCont.children('.AjaxTableCont-mapEditorContainer').remove();
- var breadcrumb = tblCont.children('.breadcrumb');
- if (!breadcrumb || !breadcrumb.length) {
- tblCont.prepend(mapDockNode);
- } else {
- mapDockNode.insertAfter(breadcrumb);
- }
- mapDockNode.append(mapEditor);
- }
- var mapDockResizable = mapEditor.parent();
- mapDockResizable.resizable({handles: 's', minHeight: 300, minWidth: 300});
- var resizeLineHeigth = 6;
- mapDockResizable.children(":first").css({height: 'auto'});
- mapDockResizable.css({marginBottom: resizeLineHeigth+'px'});
- mapEditor.css({marginBottom: resizeLineHeigth+'px'});
- mapEditor.children(":first").css({width: mapEditor.width()});
- mapDockResizable.find('.ui-resizable-s').css({height:resizeLineHeigth+'px', bottom: '-'+resizeLineHeigth+'px'});
- mapDockResizable.on('resizestart', function(event, ui) {
- ui.element.children(":first").children(":first").css({display:'none'})
- });
- mapDockResizable.on('resizestop', function(event, ui) {
- ui.element.children(":first").children(":first").css({display:'block', height: ui.element.height()});
- });
- } else if ('destroy' == task) {
- var mapDockResizable = jQuery(_uiMainContainerNode).parent('.AjaxTableCont').children('.AjaxTableCont-mapEditorContainer');
- mapDockResizable.resizable('destroy');
- mapDockResizable.remove();
- }
- };
- priv.mapEditorChanged = function(e) {
- if (priv.options.debug || DBG) console.log('mapEditorChanged option(',priv.options.mapEditor,')');
- priv.options.mapEditor = !priv.options.mapEditor;
- if (priv.options.mapEditor) {
- priv.mapEditorShow();
- }
- else {
- priv.mapEditorHide();
- }
- return false;
- };
- /*
- when: changing page in pager
- what: triggers table to be created with new page
- */
- priv.pageChanged = function(e) {
- e.preventDefault();
- var totalPages = Math.ceil(_data.total / _state.pageSize);
- if (_state.isLoadingTotal) {
- var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
- var renderedRowsCount = Math.min(_data.rows.length, _state.pageSize);
- var toRow = fromRow + renderedRowsCount;
- var total = toRow;
- if (_state.isLoadingTotal && renderedRowsCount === _state.pageSize) {
- totalPages = Math.ceil(total / _state.pageSize) + 1; // allow load next page
- }
- }
- DBG && console.warn('DBG:priv.pageChanged:?', { loadPage: e.data.pageIndex, totalPages });
- if (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
- //set the new page
- _state.page = e.data.pageIndex;
- DBG && console.warn('DBG:priv.pageChanged:', { loadPage: e.data.pageIndex });
- publ.loadPage(_state.page);
- };
- /*
- when: changing pagesize in pagesize dropdown
- what: triggers table to be created with new pagesize
- */
- priv.pageSizeChanged = function(e) {
- e.preventDefault();
- var val = $(this).text();
- if (priv.options.debug || DBG) console.log(p5Utils__format('pagesize changed to:{0}', [val]));
- if (parseInt(val) == priv.options.pageSize) {
- return false;
- }
- priv.options.pageSize = parseInt(val);
- publ.loadPage(1, priv.options.pageSize);
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['body', 'foot_pagination']);
- priv.saveProfilePageSize(priv.options.pageSize);
- };
- /*
- when: clicking a column
- what: triggers table to be sorted by the column
- */
- priv.columnClicked = function(e) {
- e.preventDefault();
- if (priv.options.debug || DBG) console.log(p5Utils__format('col:{0} clicked', [e.data.column]));
- priv.options.filterStore.dispatch( priv.options.filterActions.toggleSort(e.data.column) )
- };
- priv.saveProfilePageSize = function(pageSize) {
- var reqData = {};
- reqData.pageSize = pageSize;
- $.ajax({
- data: reqData,
- type: "POST",
- dataType: 'json',
- // async: true,
- url: priv.options.pageSizeSave
- })
- .done(function(data, textStatus, jqXHR){
- if (data && data.type && data.type == 'info') {
- jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
- } else {
- jQuery.notify('Zapisano ustawienia', 'success');
- }
- })
- .fail(function(){
- jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
- });
- };
- priv.saveHiddenCols = function() {
- var reqData = {};
- $.each(_data.cols, function(col, props) {
- if (props.type != "unique" && col != 'unique' && col != _state.primaryKey) {
- reqData[col] = (props.hidden)? 'HIDE' : 'SHOW';
- }
- });
- $.ajax({
- data: reqData,
- type: "POST",
- dataType: 'json',
- // async: true,
- url: priv.options.hiddenColsSaveUrl
- })
- .done(function(data, textStatus, jqXHR){
- if (data && data.type && data.type == 'info') {
- jQuery.notify('Nie wprowadzono żadnych zmian', 'info');
- } else {
- jQuery.notify('Zapisano ustawienia', 'success');
- }
- })
- .fail(function(){
- jQuery.notify('Wystąpił błąd podczas zapisywania ustawień', 'error');
- });
- };
- /*
- when: clicking a column in columnpicker
- what: triggers table to show/hide the column
- */
- priv.columnPickerClicked = function(e) {
- e.stopPropagation();
- var column = $(this).val();
- //toggle column visibility
- priv.modelColFilter_toggleColumn(column);
- priv.saveHiddenCols();
- //_data.cols[column].index = new priv.ext.XDate();
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['head', 'body']);
- };
- priv.modelColFilter_init = function() {// run only once, set _state._modelColFilter {selected, filters: [ {name, label, visibleCols} ]}
- var isAllSelected = true;
- if (undefined === _state._modelColFilter) {
- var columnFilters = [];
- {
- var fltrAll = {'name': 'all', 'label': 'Wszystkie', visibleCols: []};
- $.each(_data.cols, function(col, props) {
- if ("unique" == props.type) return;
- fltrAll.visibleCols.push(col);
- if (_data.cols[col].hidden) isAllSelected = false;
- });
- columnFilters.push(fltrAll);
- }
- // {
- // var fltrMostUsed = {'name': 'most_used', 'label': 'Najczęściej używane', visibleCols: []};
- // var fltrMostUsedLimit = 10;
- // $.each(_data.cols, function(col, props) {
- // if ("unique" == props.type) return;
- // if (fltrMostUsedLimit-- > 0) {
- // fltrMostUsed.visibleCols.push(col);
- // }
- // });
- // columnFilters.push(fltrMostUsed);
- // }
- _state._modelColFilter = {
- selected: (isAllSelected)? 'all' : null,
- filters: columnFilters,
- saveBtn: $('<button class="btn btn-xs btn-primary" disabled="disabled">Zapisz widoczne kolumny</button>')
- };
- _state._modelColFilter.saveBtn.on('click', priv.modelColFilter_saveBtnClicked)
- if (priv.options.userTableFilterUrl) {
- window.fetch(priv.options.userTableFilterUrl, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- credentials: 'same-origin',// add cookies
- body: JSON.stringify({
- namespace: priv.options.namespace,
- })
- }).then(function (response) {
- return response.json()
- }).then(function (result) {
- if ('success' == result.type) {
- // p5UI__notifyAjaxCallback(result)
- _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
- return ('all' === filter.name || 'most_used' == filter.name)
- }).concat(Object.keys(result.data).map(function (fltr) {
- return {
- name: fltr,
- label: fltr,
- visibleCols: result.data[fltr].split(',')
- }
- }))
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['foot__columnPicker']);
- } else {
- p5UI__notifyAjaxCallback(result)
- }
- }).catch(function (e) {
- // TODO: show error ("ajax response error: " + e)
- });
- }
- }
- };
- priv.modelColFilter_onClickRemoveFilter = function (e) {
- e.preventDefault()
- e.stopPropagation()
- var filtrName = $(this).data('col_filter')
- if (!filtrName) return
- window.fetch(priv.options.rmUserTableFilterAjaxUrl, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- credentials: 'same-origin',// add cookies
- body: JSON.stringify({
- namespace: priv.options.namespace,
- filtrName: filtrName,
- })
- }).then(function (response) {
- return response.json()
- }).then(function (result) {
- if ('success' == result.type) {
- p5UI__notifyAjaxCallback(result)
- var userTableFilters = result.data;// resolve(result.data)
- _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
- return ('all' === filter.name || 'most_used' == filter.name)
- }).concat(Object.keys(userTableFilters).map(function (fltr) {
- return {
- name: fltr,
- label: fltr,
- visibleCols: userTableFilters[fltr].split(',')
- }
- }))
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['foot__columnPicker']);
- } else {
- p5UI__notifyAjaxCallback(result)
- }
- }).catch(function (e) {
- p5UI__notifyAjaxCallback({ type: 'error', msg: new String(e) })
- });
- };
- priv.modelColFilter_saveBtnClicked = function (e) {
- swal({
- title: 'Zapisz widoczne kolumny',
- html: '',
- animation: true,
- input: 'text',
- inputPlaceholder: 'nazwa filtra',
- // inputValue: null,
- // inputAttributes: {'step': '0.01'},
- showCancelButton: true,
- confirmButtonText: 'Zapisz',
- showLoaderOnConfirm: true,
- showCloseButton: true,
- preConfirm: function(filtrName) {
- return new Promise(function(resolve, reject) {
- if (!filtrName) reject('Proszę podać nazwę filtra')
- if (filtrName.length > 255) reject('Nazwa za długa')
- window.fetch(priv.options.addUserTableFilterAjaxUrl, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json'
- },
- credentials: 'same-origin',// add cookies
- body: JSON.stringify({
- namespace: priv.options.namespace,
- filtrName: filtrName,
- visibleCols: Object.keys(_data.cols).filter(function(col) {
- return !_data.cols[col].hidden
- }).join(','),
- })
- }).then(function (response) {
- return response.text()
- }).then(function (responseText) {
- try {
- // json = response.json() // BUG: error trafia do catch promisów, zamiast aktualnego bloku
- // -- obiekt response pewnie jest powiązany z Promisem z fetch
- // -- response.json() zwraca Promise tak samo jak response.text()
- return JSON.parse(responseText)
- } catch (e) {
- throw responseText
- }
- }).then(function (result) {
- if ('success' == result.type) {
- p5UI__notifyAjaxCallback(result)
- resolve(result.data)
- } else {
- p5UI__notifyAjaxCallback(result)
- reject(result.msg || "Wystąpił błąd!")
- }
- }).catch(function (e) {
- reject("ajax response error: " + e)
- });
- })
- },
- allowOutsideClick: false
- }).then(function(userTableFilters) {
- _state._modelColFilter.filters = _state._modelColFilter.filters.filter(function (filter) {
- return ('all' === filter.name || 'most_used' == filter.name)
- }).concat(Object.keys(userTableFilters).map(function (fltr) {
- return {
- name: fltr,
- label: fltr,
- visibleCols: userTableFilters[fltr].split(',')
- }
- }))
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
- }).catch(function(e) {
- // eg. hit Cancel
- })
- }
- priv.modelColFilter_getSaveBtn = function () {
- priv.modelColFilter_init();
- return _state._modelColFilter.saveBtn
- }
- priv.modelColFilter_getFilters = function() {
- priv.modelColFilter_init();
- return _state._modelColFilter.filters;
- };
- priv.modelColFilter_getSelected = function() {
- priv.modelColFilter_init();
- return _state._modelColFilter.selected;
- };
- priv.modelColFilter_setFilter = function(filterKey) {
- priv.modelColFilter_init();
- _state._modelColFilter.selected = filterKey;
- priv.modelColFilter_uiUncheckAllColFilters();
- priv.modelColFilter_uiCheckColFilter(filterKey);
- };
- priv.modelColFilter_toggleColumn = function(column, value) {
- priv.modelColFilter_init();
- _state._modelColFilter.selected = null;
- if (!_data.cols[column] || !_data.cols[column]) return;
- _data.cols[column].hidden = (undefined !== value)? value : !_data.cols[column].hidden;
- priv.modelColFilter_uiUncheckAllColFilters();
- {
- var isAllSelected = true;
- $.each(_data.cols, function(col, props) {
- if ("unique" == props.type) return;
- if (_data.cols[col].hidden) isAllSelected = false;
- });
- if (isAllSelected) {
- _state._modelColFilter.selected = 'all';
- priv.modelColFilter_uiCheckColFilter('all');
- }
- }
- };
- priv.modelColFilter_uiUncheckAllColFilters = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
- currentNode = $(_uiMainContainerNode).next('.foot').find('.' + nodeClass)
- ;
- currentNode.find('input[type="radio"]').prop("checked", false);
- };
- priv.modelColFilter_uiCheckColFilter = function(filterKey) {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
- currentNode = $(_uiMainContainerNode).next('.foot').find('.' + nodeClass)
- ;
- currentNode.find('input[type="radio"]').each(function(idx, input) {
- var input$ = jQuery(input);
- if (filterKey == jQuery(input$).parent().data('col_filter')) {
- input$.prop("checked", true);
- } else {
- input$.prop("checked", false);
- }
- });
- };
- priv.columnPickerLinkClicked = function(e) {
- e.stopPropagation();
- var input$ = $(this).find('input'),
- col_filter = $(this).data('col_filter'),
- columnFilters = priv.modelColFilter_getFilters()
- ;
- if (col_filter) {
- var filter = null;
- $.each(columnFilters, function(idx, colFltr) {
- if (col_filter == colFltr.name) {
- filter = colFltr;
- }
- });
- if (!filter) return;
- $.each(_data.cols, function(col, props) {
- var isHidden = (-1 === filter.visibleCols.indexOf(col));
- priv.modelColFilter_toggleColumn(col, isHidden);
- });
- priv.modelColFilter_setFilter(col_filter);
- priv.saveHiddenCols();
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
- } else {
- e.preventDefault();
- if (input$.length != 1) return;
- var column = input$.val();
- if (!column) return;
- //toggle column visibility
- priv.modelColFilter_toggleColumn(column);
- input$.prop("checked", !input$.is(':checked'));// update view
- priv.saveHiddenCols();
- //_data.cols[column].index = new priv.ext.XDate();
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['head', 'body']);
- }
- };
- priv.columnHideClicked = function(e) {
- e.stopPropagation();
- var column;
- if (e.data && e.data.column) {
- column = e.data.column;
- } else {
- return;
- }
- //toggle column visibility
- priv.modelColFilter_toggleColumn(column);
- priv.saveHiddenCols();
- //_data.cols[column].index = new priv.ext.XDate();
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
- };
- priv.hideColumn = function(fieldName) {
- priv.modelColFilter_toggleColumn(fieldName);
- priv.saveHiddenCols();
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', ['head', 'body', 'foot__columnPicker']);
- };
- /*
- when: clicking anywhere on a row
- what: row data and other info is returned to caller
- */
- // priv.rowClicked = function(e) {// TODO: not used
- // if (!_state.primaryKey) {
- // if (priv.options.debug || DBG) console.log('no unique column specified');
- // return;
- // }
- //
- // //gather callback data
- // var elem = $(this);
- // var column = _data.cols[elem.data('column')];
- // var unique = elem.closest('tr').data('unique');
- // var row = priv.getRow(unique);
- // var isChecked = elem.closest('tr').find('.unique').is(':checked');
- //
- // //trigger callback
- // if (typeof priv.options.rowClicked == 'function') {
- // priv.options.rowClicked.call(e.target, {
- // event: e,
- // row: row,
- // column: column,
- // checked: isChecked
- // });
- // }
- // };
- /**
- * Inline edit.
- */
- priv.rowDblClicked = function(e) { // TODO: export outside (handle in table router file)
- var inlineEditBox$Node = $(_uiMainContainerNode).parent().children('.tblAjax__inlineEditBox');
- // hide popover for typespecial fld on click
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('hide');
- }
- // e.clientX: 1002; e.clientY: 245
- if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
- inlineEditBox$Node.modal();
- inlineEditBox$Node.show();
- inlineEditBox$Node.on('shown.bs.modal', function(e) {
- var dialogBox = jQuery(this).find('.modal-dialog'),
- modalBody = dialogBox.find('.modal-body'),
- boudingRect = dialogBox.get(0).getBoundingClientRect();
- dialogBox.css({position: 'absolute', margin:0, top: boudingRect.top, left: boudingRect.left});
- modalBody.css({overflow: 'scroll'});
- dialogBox.resizable({minHeight: 300, minWidth: 300, alsoResize: modalBody});
- dialogBox.draggable({handle: '.modal-header'});
- });
- inlineEditBox$Node.on('hidden.bs.modal', function(e) {
- var dialogBox = jQuery(this).find('.modal-dialog'),
- modalBody = dialogBox.find('.modal-body');
- dialogBox.removeAttr('style');
- modalBody.removeAttr('style');
- modalBody.css({padding: '0'});
- dialogBox.resizable();
- dialogBox.draggable();
- dialogBox.resizable('destroy');
- dialogBox.draggable('destroy');
- });
- inlineEditBox$Node.find('input[name=ID]').val(e.data.id);
- inlineEditBox$Node.find('input[name=col]').val(e.data.col);
- inlineEditBox$Node.find('.inlineEditBox-cnt').html('<span class="loading-info"> loading ...</span>');
- $.ajax({
- url: priv.options.editInlineUrl + '&ID=' + e.data.id + '&col=' + e.data.col,
- type: 'GET',
- dataType: 'json',
- success: function(data) {
- if ('p5:www_link' == _.get(data, 'simpleType')) {
- inlineEditBox$Node.find('.inlineEditBox-cnt').empty();
- var label = jQuery('<label>');// for="' + data.htmlFieldName + '">');// "<label for="f22579" class="AjaxTableEdit-label"> ... </label>
- label.attr('for', data.htmlFieldName);
- label.attr('class', 'AjaxTableEdit-label');
- inlineEditBox$Node.find('.inlineEditBox-cnt').append(label);
- var inLabel = jQuery('<strong title="[' + data.idZasob + '] ' + data.fieldLabel + '">' + data.fieldLabel + '</strong>');
- label.append(inLabel);
- var frmItem = jQuery('<input>');
- frmItem.attr('type', 'text');
- frmItem.attr('name', data.htmlFieldName);
- frmItem.attr('value', data.formItem.value);
- frmItem.attr('maxlength', _.get(data, 'restrictions.maxLength', 255));
- frmItem.attr('style', 'width:98%');
- frmItem.attr('class', 'form-control');
- frmItem.insertAfter(label);
- } else {
- var content = _.get(data, 'legacy_html', "Nieznany błąd");
- inlineEditBox$Node.find('.inlineEditBox-cnt').html(content);
- }
- inlineEditBox$Node.find('.btn-save').show();
- initDateTimePicker(inlineEditBox$Node);
- inlineEditBox$Node.find('textarea').autosize();
- var fld = inlineEditBox$Node.find('input[name^="f"]');
- if (fld.length > 0 && !fld.hasClass('se_type-date')) {
- fld.keydown(function(event) {
- if (event.which == 13) {
- event.preventDefault();
- inlineEditBox$Node.find('form').submit();
- }
- });
- }
- (function setFocusAtFirstInlineEditFormFld(modal$node){
- var fld, dbg = false;
- if(dbg)console.log('focus...');
- fld = modal$node.find('input[name^="f"]:first');
- if (fld.length > 0 && !fld.hasClass('se_type-date')) {
- if(dbg)console.log('set focus to first input element');
- fld.focus(); return;
- }
- fld = modal$node.find('select[name^="f"]:first');
- if (fld.length) {
- if (fld.get(0).selectize) {
- if(dbg)console.log('set focus to first typepecial element');
- } else {
- if(dbg)console.log('set focus to first select element');
- fld.focus(); return;
- }
- }
- if(dbg)console.log('set focus to close btn');
- modal$node.find('.btn-close').focus();
- })(inlineEditBox$Node);
- },
- error: function(err) {
- if (priv.options.debug || DBG) console.log('err');
- }
- });
- } else {
- if (priv.options.debug || DBG) console.log('NO data');
- return false;
- }
- };
- priv.ajaxLoadTypeSpeciallCell = function(id, col) {
- if (_popoverCellAjaxXhr) {
- _popoverCellAjaxXhr.abort();
- }
- _popoverCellAjaxXhr = $.ajax({
- type: 'GET',
- url: 'index.php?_route=ViewTableAjax&_task=typeSpecialCell&namespace=' + priv.options.namespace + '&ID=' + id + '&col=' + col,
- dataType: 'json',
- contentType: "application/json; charset=utf-8",
- data: '',
- success: function(req){
- if (_.get(req, 'data.tbl_id') > 0) {
- var addHtml = '';
- for (var i in req.data.items) {
- var url = 'index.php?_route=ViewTableAjax';
- url += '&namespace=' + req.namespace;
- url += '&f_' + req.data.fld_name + '=' + req.data.items[i].id;
- url += '&_hash=' + Math.random().toString(36).substring(2);
- addHtml += '<a href="' + url + '">Wyszukaj ' + req.data.items[i].id + '</a>: ' + req.data.items[i].label;
- addHtml += '<br>';
- }
- //_popoverCell.append(addHtml);// cache
- if (_popoverCellCurrent) {
- var popoverNodeId = _popoverCellCurrent.attr('aria-describedby');
- if (popoverNodeId) {
- jQuery('#' + popoverNodeId).find('.popoverCellContent').append(addHtml);
- }
- }
- }
- }
- });
- };
- priv.popoverCellTypeSpecial = function(e) {
- e.preventDefault();
- e.stopPropagation();
- if ('id' in e.data && 'col' in e.data && e.data.id > 0) {
- var lastId = _popoverCell.data('rowid'),
- lastCol = _popoverCell.data('col'),
- rowPK = e.data.id,
- colName = e.data.col
- ;
- if (lastId == rowPK && lastCol == colName) {
- //_popoverCellCurrent.popover('toggle');
- }
- else {
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('destroy');
- }
- _popoverCell.data('rowid', rowPK);
- _popoverCell.data('col', colName);
- _popoverCell.html(e.data.value + '<div class="popoverCellContent loading" style="white-space:normal"></div>');
- _popoverCellCurrent = jQuery(e.currentTarget);
- // title : '<span class="text-info"><strong>title</strong></span> <button type="button" id="close" class="close">×</button>'
- var opts = {
- placement: 'left'
- , trigger: 'click'
- // , title: e.data.col + '<a href="#" class="glyphicon glyphicon-remove pull-right" onclick="return hidePopover();"></a>'
- , 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;">×</button>' + '</div>'
- , html: true
- , content: _popoverCell.html()
- }
- _popoverCellCurrent.popover(opts);
- if (_data.cols[colName]) {
- if (_data.cols[colName]._tsRetId > 0) {
- _popoverCellCurrent.on('shown.bs.popover', function() {
- priv.ajaxLoadTypeSpeciallCell(rowPK, colName);
- });
- }
- }
- _popoverCellCurrent.popover('show');
- }
- } else {
- if (priv.options.debug || DBG) console.log('NO data');
- return false;
- }
- return;
- };
- priv.routeChanged = function(e) {
- hash = e.data.hash || '';
- if (hash.length == 0) {
- return;
- }
- if (hash.substring(0, 1) != '#') {
- hash = '#' + hash;
- }
- location.hash = hash;
- };
- priv.refresh = function(e) {
- e.preventDefault();
- publ.loadPage(_state.page);
- };
- publ.init = function(options) {
- if (priv.options.debug || DBG) console.log('TableAjax initialization...');
- //merge supplied options with defaults
- $.extend(priv.options, defaults, options);
- priv.init();
- return publ;
- };
- publ.refresh = function() {
- publ.loadPage(_state.page);
- };
- publ.loadPage = function(page, pageSize) {
- priv.loadPage(page, pageSize);
- }
- priv.asyncFetchTotal = function(url) {
- var this__asyncFetchTotal__reqId = (_state.asyncFetchTotal__lastSentReqId || 0) + 1;
- { // prevent to fetch more then 2 requests at the same time
- var lastReceivedId = _state.asyncFetchTotal__lastReceivedId || 0;
- DBG && console.log('DBG:priv.asyncFetchTotal skip', { skip: (this__asyncFetchTotal__reqId > lastReceivedId + 2), lastSentReqId: this__asyncFetchTotal__reqId, lastReceivedId: lastReceivedId })
- if (this__asyncFetchTotal__reqId > lastReceivedId + 2) return;
- }
- _state.asyncFetchTotal__lastSentReqId = this__asyncFetchTotal__reqId;
- window.fetch(url, {
- method: priv.options.urlPost ? 'POST' : 'GET',
- credentials: 'same-origin',
- }).then(function(response) {
- return response.json()
- }).then(function (data) {
- if ('success' == data.type) {
- _data.total = data.total || -1;
- DBG && console.log('DBG:priv.asyncFetchTotal fetch success', { reqId: this__asyncFetchTotal__reqId, data: data })
- if (SKIP_TOTAL) _state.asyncFetchTotal__lastReceivedId = this__asyncFetchTotal__reqId;
- if (SKIP_TOTAL) _state.isLoadingTotal = (_state.asyncFetchTotal__lastReceivedId < _state.asyncFetchTotal__lastSentReqId);
- jQuery(_uiMainContainerNode).trigger('TableAjax:render', [ 'foot_pagination' ]);
- } else {
- p5UI__notifyAjaxCallback(data);
- // priv.showFailFetchDataMsg();
- }
- }).catch(function (e) {
- console.log('asyncFetchTotal:fetch: ERR:', e);
- })
- }
- priv.loadPage = function(page, pageSize) {
- var resetChecked = false;
- var reqData = {
- page: page,
- pageSize: (pageSize || priv.options.pageSize),
- currSortCol: (_state._currSortCol || ''),
- currSortFlip: _state._currSortFlip ? "desc" : "asc"
- };
- var urlAdd = '';
- urlAdd += '&' + 'page=' + page;
- urlAdd += '&' + 'pageSize=' + (pageSize || priv.options.pageSize);
- DBG && console.log('DBG::loadPage... FETCH_DATA', { '_state._filterQuery': _state._filterQuery, '_state._specialFilterQuery': _state._specialFilterQuery, _state });
- urlAdd += '&' + priv.filter_getFullFilterQuery();
- if (SKIP_TOTAL) urlAdd += '&' + 'SKIP_TOTAL=1';
- _uiNode$Table.parent().parent().addClass('AjaxTable-loading');
- // p5UI__notifyAjaxCallback({type: 'info', msg: 'pobieranie danych...'});
- window.fetch(priv.options.url + urlAdd, {
- method: priv.options.urlPost ? 'POST' : 'GET',
- credentials: 'same-origin',// add cookies
- }).then(function (response) {
- return response.json()
- }).then(function (data) {
- if (priv.options.debug || DBG) console.log('loadDataAjax:fetch:loadPage: request finished, data:', data);
- // p5UI__notifyAjaxCallback(data);
- if ('success' == data.type) {
- state = {data: {}};
- state.data.cols = data.cols || {};
- state.data.rows = data.rows || [];
- state.data.total = data.total || 0;
- state.data.primaryKey = data.primaryKey || 'ID';
- state.page = data.page || 0;
- state.pageSize = data.pageSize || priv.options.pageSize;
- state.filters = data.filters || {};
- DBG && console.log('DBG::loadPage... - FETCH_DATA END priv.setState(state);', { state });
- if (SKIP_TOTAL) _state.isLoadingTotal = true;
- priv.setState(state);
- _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
- if (SKIP_TOTAL) priv.asyncFetchTotal((priv.options.url + urlAdd).replace('SKIP_TOTAL=1', 'ONLY_TOTAL=1'))
- } else {
- p5UI__notifyAjaxCallback(data);
- priv.showFailFetchDataMsg();
- }
- }).catch(function (e) {
- console.log('loadDataAjax:fetch: ERR:', e);
- });
- };
- publ.getCurrentPage = function() {
- return _state.page;
- };
- publ.popoverCellRemove = function() {
- if (_popoverCellCurrent) {
- _popoverCellCurrent.popover('destroy');
- }
- _popoverCell.data('rowid', -1);
- _popoverCell.data('col', -1);
- _popoverCell.html('');
- };
- return publ;
- }
- $.fn.TableAjax = function(options) {
- options = options || {};
- return this.each(function() {
- options.mainContainerNode = this;
- $(this).data('TableAjax', new TableAjax().init(options));
- });
- };
- $.fn.TableAjaxLoadPage = function(page, pageSize) {
- return this.each(function() {
- var tblAjax = jQuery(this).data('TableAjax');
- var curPage = page || tblAjax.getCurrentPage();
- if (tblAjax) tblAjax.loadPage(curPage, pageSize);
- });
- };
- $.fn.TableAjaxRefresh = function(page, pageSize) {
- return this.each(function() {
- var tblAjax = jQuery(this).data('TableAjax');
- if (tblAjax) tblAjax.refresh();
- });
- };
|