| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848 |
- 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 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";
- var createReactClass = global.p5VendorJs.createReactClass;
- var h = global.p5VendorJs.React.createElement;
- 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'];
- 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;
- };
- }
- 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;
- }
- };
- })();
- var p5WPSUtils__createConvertToWpsDataInputFunction = function (identifier) {
- return function (value) {
- if (!value) return null; // WPS function require value, but for eg. featureQuery mey be empty
- return { // "wps:Input"
- identifier: identifier, // "ows:Identifier"
- // title: "...", // "ows:Title"
- data: { literalData: { value: value } }, // "wps:Data"
- // reference: "???", // "wps:Reference"
- // boundingBoxData: "???", // "wps:BoundingBoxData"
- };
- }
- };
- var p5WPSHelper_generateProcessSelectFeatureWithArgs = function (identifier, args) {
- var dataInputs = Object.keys(args).reduce(function (ret, argName) {
- var value = args[argName];
- var convertValueToWpsDataInput = p5WPSUtils__createConvertToWpsDataInputFunction(argName);
- return (p5Utils__isArray(value))
- ? ret.concat( value.map( convertValueToWpsDataInput ) )
- : ret.concat([ convertValueToWpsDataInput(value) ])
- ;
- }, []).filter(function (wpsTag) {
- return !! wpsTag;
- })
- return {
- identifier: identifier, // "ows:Identifier"
- dataInputs: dataInputs,
- responseForm: { // "wps:ResponseForm"
- // rawDataOutput: "???", // "wps:RawDataOutput"
- // responseDocument: "???", // "wps:ResponseDocument"
- }
- }
- }
- var p5WPS_executeFeatureProcess = function(identifier) {
- return function (wpsArgs) { // TODO: ns, listPrimaryKeys
- return new Promise(function (resolve, reject) {
- var process = p5WPSHelper_generateProcessSelectFeatureWithArgs(identifier, wpsArgs);
- OpenLayers.Request.POST({
- url: URI_WPS,
- data: new OpenLayers.Format.WPSExecute().write(process),
- callback: function (response) {
- try {
- var txt = response.responseText || ''
- if (!txt) throw "Empty response";
- var responseJson = JSON.parse(txt)
- if ('success' != responseJson.type) throw "Error response type '" + responseJson.type + "'";
- if (!responseJson.body || !responseJson.body.selected) throw "Brak danych";
- var listSelectedPks = Object.keys(responseJson.body.selected).filter(function (pk) {
- return responseJson.body.selected[pk];
- })
- var totalSelected = responseJson.body.totalSelected;
- DBG && console.log('wps('+identifier+') response', {response, responseJson, selected: responseJson.body.selected, resolve: listSelectedPks});
- resolve({
- selected: listSelectedPks,
- totalSelected: totalSelected,
- })
- } catch (e) {
- reject('' + e)
- return;
- }
- },
- // success: function (response) {
- // },
- // failure: function (response) {
- // }
- });
- });
- }
- };
- var p5WPS__selecFeature = p5WPS_executeFeatureProcess('p5:selectFeature');
- var p5WPS__unselectFeature = p5WPS_executeFeatureProcess('p5:unselectFeature');
- var p5WPS__unselecAllFeatures = p5WPS_executeFeatureProcess('p5:unselectAllFeatures');
- var p5WPS__getSelectedFeatures = p5WPS_executeFeatureProcess('p5:getSelectedFeatures');
- var p5WPS__selectAllFeaturesMatchingFilter = p5WPS_executeFeatureProcess('p5:selectAllFeaturesMatchingFilter');
- function p5Utils__arrayRemove(array, toRemoveItem) {
- return array.filter(function (item) {
- return ( item !== toRemoveItem );
- });
- }
- 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 fixSelectAllInSelectedState(state) {
- var len = state.listPrimaryKeys.length;
- var selLen = state.selected.length;
- var isAllSelected = ( len > 0 && selLen >= len ); // selected array may contain 'select-all'
- for (var i = 0, pk = ''; i < len; i++) {
- pk = state.listPrimaryKeys[i];
- if (-1 === state.selected.indexOf(pk)) {
- isAllSelected = false;
- break;
- }
- }
- // DBG && console.log('fixSelectAllInSelectedState', { isAllSelected, state });
- var isSelectedSelectAll = ( -1 !== state.selected.indexOf('select-all') );
- if (isAllSelected && !isSelectedSelectAll) return Object.assign(state, {
- selected: ['select-all'].concat(state.selected)
- });
- if (!isAllSelected && isSelectedSelectAll) return Object.assign(state, {
- selected: p5Utils__arrayRemove(state.selected, 'select-all'),
- });
- return state;
- }
- function selectedStore(state, action) {
- var prevState = state || { isLoading: false, selected: [], loading: [], listPrimaryKeys: [], totalSelected: 0 };
- DBG && console.log('DBG::selectedStore', { prevState, action });
- switch (action.type) {
- case 'SET_CHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
- loading: p5Utils__arrayRemove(prevState.loading, action.primaryKey),
- selected: prevState.selected.concat(action.primaryKey),
- totalSelected: action.totalSelected,
- }));
- case 'SET_UNCHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
- loading: p5Utils__arrayRemove(prevState.loading, action.primaryKey),
- selected: p5Utils__arrayRemove(prevState.selected, action.primaryKey),
- totalSelected: action.totalSelected,
- }));
- case 'SET_LIST_CHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
- loading: [], // TODO: p5Utils__arrayExcept(prevState.loading, action.listPrimaryKeys),
- selected: [].concat(action.listPrimaryKeys), // TODO: p5Utils__arrayUniqueUnion(prevState.selected, action.listPrimaryKeys)
- totalSelected: action.totalSelected,
- }));
- case 'SET_LIST_UNCHECKED': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
- loading: [], // TODO: p5Utils__arrayExcept(prevState.loading, action.listPrimaryKeys),
- selected: [], // TODO: p5Utils__arrayUniqueUnion(prevState.selected, action.listPrimaryKeys)
- totalSelected: action.totalSelected,
- }));
- case 'SET_LOADING': return Object.assign(prevState, {
- loading: prevState.loading.concat(action.primaryKey)
- });
- case 'SET_LIST_LOADING': return Object.assign(prevState, {
- loading: [].concat(action.listPrimaryKeys)
- });
- case 'SET_PRIMARY_KEYS': return fixSelectAllInSelectedState(Object.assign({}, prevState, {
- listPrimaryKeys: [].concat(action.listPrimaryKeys),
- loading: [].concat(action.listPrimaryKeys)
- }));
- // case 'SET_ERROR_MSG': return Object.assign(prevState, {
- // errorMsg: action.errorMsg
- // });
- default: return prevState;
- }
- }
- function selectedActions(idContext) {
- var idContext = idContext || null;
- function setChecked(primaryKey, totalSelected) {
- return { type: 'SET_CHECKED', primaryKey: primaryKey, totalSelected: totalSelected }
- }
- function setUnchecked(primaryKey, totalSelected) {
- return { type: 'SET_UNCHECKED', primaryKey: primaryKey, totalSelected: totalSelected }
- }
- function setLoading(primaryKey) {
- return { type: 'SET_LOADING', primaryKey: primaryKey }
- }
- function setListChecked(listPrimaryKeys, totalSelected) {
- return { type: 'SET_LIST_CHECKED', listPrimaryKeys: listPrimaryKeys, totalSelected: totalSelected }
- }
- function setListUnchecked(listPrimaryKeys, totalSelected) {
- return { type: 'SET_LIST_UNCHECKED', listPrimaryKeys: listPrimaryKeys, totalSelected: totalSelected }
- }
- function setListLoading(listPrimaryKeys) {
- return { type: 'SET_LIST_LOADING', listPrimaryKeys: listPrimaryKeys }
- }
- function setErrorMsg(errorMsg) {
- return { type: 'SET_ERROR_MSG', errorMsg: errorMsg }
- }
- function toggle(namespace, primaryKey, checked) {
- if ('select-all' === primaryKey) return toggleAll(namespace, checked);
- return function(dispatch, getState) {
- // var state = getState();
- dispatch(setLoading(primaryKey));
- var reqArgs = { typeName: namespace, primaryKey: [ primaryKey ] };
- if (idContext) reqArgs.idContext = idContext;
- var reqPromise = checked ? p5WPS__selecFeature(reqArgs) : p5WPS__unselectFeature(reqArgs);
- return reqPromise.then(function (response) {
- DBG && console.log('DBG::async toggle action: (pk:'+primaryKey+') dispatch...');
- dispatch( checked ? setChecked(primaryKey, response.totalSelected) : setUnchecked(primaryKey, response.totalSelected) );
- }).catch(function (e) {
- p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA1: ' + e});
- DBG && console.warn('DBG::async toggle action: (pk:'+primaryKey+') ERROR', e);
- // dispatch( checked ? setUnchecked(primaryKey) : setChecked(primaryKey) );
- // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
- dispatch( setListLoading([]) );
- });
- }
- }
- function setPrimaryKeys(namespace, listPrimaryKeys) { // TODO: should set list primaryKeys, change checkboxes to loading and fetch its state, then update gui
- DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+'])...');
- return function(dispatch, getState) {
- dispatch({ type: 'SET_PRIMARY_KEYS', listPrimaryKeys: listPrimaryKeys });
- // dispatch( setListLoading(listPrimaryKeys) );
- if (!listPrimaryKeys.length) return;
- var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys };
- if (idContext) reqArgs.idContext = idContext;
- return p5WPS__getSelectedFeatures(reqArgs).then(function (listSelected) {
- DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
- dispatch( setListChecked(listSelected.selected, listSelected.totalSelected) );
- }).catch(function (e) {
- p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA2: ' + e});
- DBG && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
- // var fullListPks = ['select-all'].concat(listPrimaryKeys);
- // dispatch( setListUnchecked(fullListPks) );
- // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
- dispatch( setListLoading([]) );
- });
- }
- }
- function toggleAll(namespace, checked) {
- var primaryKey = 'select-all';
- return function(dispatch, getState) {
- // var state = getState();
- dispatch(setLoading(primaryKey));
- var state = getState();
- var listPrimaryKeys = state.listPrimaryKeys;
- var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys };
- if (idContext) reqArgs.idContext = idContext;
- var reqPromise = checked ? p5WPS__selecFeature(reqArgs) : p5WPS__unselectFeature(reqArgs);
- return reqPromise.then(function (response) {
- DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
- dispatch( checked ? setListChecked(response.selected, response.totalSelected) : setListUnchecked(response.selected, response.totalSelected) );
- }).catch(function (e) {
- p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA3: ' + e});
- DBG && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
- // var fullListPks = ['select-all'].concat(listPrimaryKeys)
- // dispatch( checked ? setListUnchecked(fullListPks) : setListChecked(fullListPks) );
- // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
- dispatch( setListLoading([]) );
- });
- }
- }
- function unselectAll(namespace) {
- // dispatch(setLoading());
- return function(dispatch, getState) {
- var reqArgs = { typeName: namespace };
- if (idContext) reqArgs.idContext = idContext;
- var reqPromise = p5WPS__unselecAllFeatures(reqArgs);
- return reqPromise.then(function (response) {
- DBG && console.log('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) dispatch success');
- // dispatch( setListChecked(response.selected, response.totalSelected) );
- dispatch( setListChecked([], 0) );
- }).catch(function (e) {
- p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA4: ' + e});
- DBG && console.warn('DBG::setPrimaryKeys action: (pks:['+listPrimaryKeys.join(',')+']) ERROR dispatch error');
- // var fullListPks = ['select-all'].concat(listPrimaryKeys)
- // dispatch( checked ? setListUnchecked(fullListPks) : setListChecked(fullListPks) );
- // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
- // dispatch( setListLoading([]) );
- });
- };
- }
- function selectAllMatchingFilter(namespace, filterQuery) {
- DBG && console.log('DBG::selectAllMatchingFilter', { filterQuery });
- return function(dispatch, getState) {
- DBG && console.log('DBG::selectAllMatchingFilter state', state);
- var state = getState();
- var listPrimaryKeys = state.listPrimaryKeys;
- var reqArgs = { typeName: namespace, primaryKey: listPrimaryKeys, filterQuery: filterQuery };
- if (idContext) reqArgs.idContext = idContext;
- return p5WPS__selectAllFeaturesMatchingFilter(reqArgs).then(function (listSelected) {
- DBG && console.log('DBG::selectAllMatchingFilter dispatch success');
- dispatch( setListChecked(listSelected.selected, listSelected.totalSelected) );
- }).catch(function (e) {
- p5UI__notifyAjaxCallback({type: 'error', msg: 'Wystąpił błąd #TA5: ' + e});
- DBG && console.warn('DBG::selectAllMatchingFilter ERROR dispatch error');
- // var fullListPks = ['select-all'].concat(listPrimaryKeys);
- // dispatch( setListUnchecked(fullListPks) );
- // dispatch( setErrorMsg(e) ); // TODO: show error with msg and refresh button
- dispatch( setListLoading([]) );
- });
- }
- }
- return {
- setPrimaryKeys: setPrimaryKeys,
- setChecked: setChecked,
- setUnchecked: setUnchecked,
- toggle: toggle,
- unselectAll: unselectAll,
- selectAllMatchingFilter: selectAllMatchingFilter,
- }
- }
- global['P5UI__TableAjaxRowCheckbox'] = createReactClass({
- // props.namespace: PropTypes.string.isRequired
- // props.primaryKey: 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();
- return {
- disabled: this.props.disabled ? true : false,
- isLoading: (-1 !== state.loading.indexOf(this.props.primaryKey)),
- checked: (-1 !== state.selected.indexOf(this.props.primaryKey))
- };
- },
- getInitialState: function () {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::componentDidMount (pk:'+this.props.primaryKey+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::storeUpdated (pk:'+this.props.primaryKey+')');
- this.setState(this.getStateFromStore())
- },
- shouldComponentUpdate: function (nextProps, nextState) {
- DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::shouldComponentUpdate (pk:'+this.props.primaryKey+')', { state: this.state, nextState});
- return (
- this.state.isLoading !== nextState.isLoading
- || this.state.checked !== nextState.checked
- );
- },
- handleChange: function (checked) { // handleChange: function (event) {
- DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::handleChange (pk:'+this.props.primaryKey+')', { checked: checked });
- this.props.store.dispatch( this.props.actions.toggle( this.props.namespace, this.props.primaryKey, checked ) )
- },
- render: function () {
- DBG && console.log('DBG::P5UI__TableAjaxRowCheckbox::render (pk:'+this.props.primaryKey+')', { props: this.props, state: this.state });
- return h(p5UI__FieldCheckboxLoading, {
- size: 20,
- color: '#999',
- checked: this.state.checked,
- disabled: this.state.disabled,
- isLoading: this.state.isLoading,
- onChange: this.handleChange
- });
- }
- });
- global['P5UI__TableAjaxSelectedInfo'] = createReactClass({
- // props.namespace: 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();
- var wasAllSelected = (this.state) && this.state.isUpdatedAllSelected;
- var isAllSelected = ( -1 !== state.selected.indexOf('select-all') );
- DBG && console.log('DBG: getStateFromStore (ns:'+this.props.namespace+')', { isAllSelected, state });
- return {
- // isLoading: state.isLoading || 0, // add ?
- isUpdatedAllSelected: ( !wasAllSelected && isAllSelected ),
- totalSelected: state.totalSelected || 0,
- };
- },
- getInitialState: function () {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::componentDidMount (ns:'+this.props.namespace+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::storeUpdated (ns:'+this.props.namespace+')');
- this.setState(this.getStateFromStore())
- },
- shouldComponentUpdate: function (nextProps, nextState) {
- DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::shouldComponentUpdate (ns:'+this.props.namespace+')', { state: this.state, nextState});
- return (
- this.state.totalSelected !== nextState.totalSelected
- || this.state.isUpdatedAllSelected !== nextState.isUpdatedAllSelected
- );
- },
- handleUnselectAll: function (event) {
- DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::handleUnselectAll (ns:'+this.props.namespace+')');
- this.props.store.dispatch( this.props.actions.unselectAll( this.props.namespace ) )
- },
- handleSelectAllByFilter: function (event) {
- DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::handleSelectAllByFilter (ns:'+this.props.namespace+')');
- // this.props.store.dispatch( this.props.actions.unselectAll( this.props.namespace ) )
- this.props.onSelectAllMatching()
- },
- render: function () {
- DBG && console.log('DBG::P5UI__TableAjaxSelectedInfo::render (ns:'+this.props.namespace+')', { props: this.props, state: this.state });
- return h('div', { style: {
- padding: '0 4px'
- } }, [
- h('span', {}, "Wybrano " + this.state.totalSelected),
- (this.state.totalSelected > 0) ? h('i', {
- onClick: this.handleUnselectAll,
- className: "glyphicon glyphicon-remove",
- style: {
- marginLeft: '4px',
- cursor: 'pointer',
- color: 'red',
- opacity: '0.5'
- },
- title: this.props.title || 'Usuń wszystkie zaznaczenia'
- }) : null,
- (this.state.isUpdatedAllSelected) && h('br'),
- (this.state.isUpdatedAllSelected) && h('a', {
- onClick: this.handleSelectAllByFilter,
- className: "btn btn-xs btn-link",
- style: {
- marginLeft: '4px',
- },
- title: this.props.title || 'Zaznacz wszystkie pasujące do wyszukiwania'
- }, "+ wszystkie"),
- ])
- }
- });
- 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),
- }, 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,
- }, [
- 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: { color: !this.state.selected ? '#bbb' : '#f00' }
- }, [
- 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__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,
- active: ('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::P5UI__TableAjaxFieldCheckboxSearch::componentDidMount (f:'+this.props.fieldName+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::P5UI__TableAjaxFieldCheckboxSearch::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
- this.setState(this.getStateFromStore())
- },
- shouldComponentUpdate: function (nextProps, nextState) {
- DBG && console.log('DBG::P5UI__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::P5UI__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::P5UI__TableAjaxFieldCheckboxSearch::render (f:'+this.props.fieldName+')', { props: this.props, state: this.state, state_sel: this.state.selected, sel: this.mapSelectedToValue(this.state.selected) });
- return h('div',
- {
- style: {
- boxSizing: 'border-box', width: '100%', height: '21px', padding: '0 5px', borderTop: 0,
- borderBottom: '2px solid ' + ( this.state.active ? '#00ACCC' : 'transparent' ),
- },
- }, [
- h(p5UI__FieldCheckboxSearch, {
- size: 19,
- color: '#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) || '',
- active: 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.active !== nextState.active
- );
- },
- 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.active ? " filter-active" : "" ),
- 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.active ? '#00ACCC' : 'transparent' ),
- },
- 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 {
- isFiltersEmpty: ( 0 === storeState.filter.size && 0 === storeState.specialFilter.size )
- };
- },
- getInitialState: function() {
- return this.getStateFromStore();
- },
- componentDidMount: function () {
- DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::componentDidMount (f:'+this.props.fieldName+')');
- this.unsubscribe = this.props.store.subscribe(this.storeUpdated)
- },
- componentWillUnmount: function () {
- this.unsubscribe()
- },
- storeUpdated: function () {
- DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::storeUpdated (f:'+this.props.fieldName+')', this.getStateFromStore());
- this.setState(this.getStateFromStore())
- },
- // shouldComponentUpdate: function (nextProps, nextState) {
- // DBG && console.log('DBG::p5UI__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::p5UI__TableAjaxClearAllFilters::handleClick (clearAllFilters)');
- this.props.store.dispatch( this.props.actions.clearAllFilters() )
- },
- render: function () {
- DBG && console.log('DBG::p5UI__TableAjaxClearAllFilters::render (clearAllFilters)', { props: this.props, state: this.state });
- return 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.isFiltersEmpty ? { color: '#777' } : { color: '#f00' }
- ),
- 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,
- filtersClean: false,
- router: false,
- longDesc: false,
- exportFields: [],
- mapEditor: false, // mapEditor visible or not
- mapEditorContainer: 'window' // 'window' or 'dock'
- };
- var _uiNodeCont; // container holding table
- var _uiNodeSelectedInfo;
- var _uiNodeSpecialFilters;
- var _uiNode$Table; // the table node
- var _head; // table header
- var _headSort; // table header sorting row
- var _headFilter; // table header columns filter row
- 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 _totalPages; // total pages
- 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() {
- _uiNodeCont = priv.options.id;
- _state = {};// init state
- _state.page = 1;
- _state.specialFilters = {};
- { // init events
- jQuery(_uiNodeCont).on('TableAjax:render', priv.onRender);
- jQuery(window).on('resize', priv.onWindowResize)
- }
- priv.initialRender();// set up _uiNode$...
- 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 stateObjectFilter = createTableFiltersStateObject(priv.options.filterInit || {});
- priv.options.filterStore = stateObjectFilter.store;
- priv.options.filterActions = stateObjectFilter.actions;
- // priv.options._filterState = Object.assign({}, priv.options.filterStore.getState())
- var curFilterState = priv.options.filterStore.getState()
- _state._filterQuery = p5Utils__mapToQueryWithKeyPrefix(curFilterState.filter, 'f_')
- _state._specialFilterQuery = p5Utils__mapToQueryWithKeyPrefix(curFilterState.specialFilter, 'sf_')
- _state._currSortCol = curFilterState.currSortCol;
- _state._currSortFlip = curFilterState.currSortFlip;
- DBG && console.log('TODO:INIT: ', { _state });
- priv.options.filterStore.subscribe(function () {
- curState = priv.options.filterStore.getState()
- var curFilterQuery = p5Utils__mapToQueryWithKeyPrefix(curState.filter, 'f_')
- var curSpecialFilterQuery = p5Utils__mapToQueryWithKeyPrefix(curState.specialFilter, 'sf_')
- var needFetchData = (
- curFilterQuery !== _state._filterQuery
- || curSpecialFilterQuery !== _state._specialFilterQuery
- || curState.currSortCol !== _state._currSortCol
- || curState.currSortFlip !== _state._currSortFlip
- );
- DBG && console.log('TODO:filtersUpdated - FETCH_DATA: ', { _state, curState });
- _state._filterQuery = curFilterQuery;
- _state._specialFilterQuery = curSpecialFilterQuery;
- _state._currSortCol = curState.currSortCol;
- _state._currSortFlip = curState.currSortFlip;
- if (needFetchData) {
- DBG && console.log('TODO:filtersUpdated - FETCH_DATA: ', { curFilterQuery, curSpecialFilterQuery });
- priv.loadPage(0)
- }
- })
- if (priv.options.checkboxes) {
- priv.options.selectedStore = createStoreWithThunkMiddleware(selectedStore)
- priv.options.selectedActions = selectedActions(idContext = priv.options.checkboxIdContext)
- 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,
- onSelectAllMatching: function () {
- 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
- );
- }
- }
- if (location.hash) {
- priv.options.router()
- } else {
- priv.update(priv.options.router)
- }
- if (typeof priv.options.router == "function") {
- $(window).bind('hashchange', function() {
- priv.options.router.apply(this);
- });
- }
- };
- 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(_uiNodeCont).parent().width();
- var colsW = stickyCol1Width + stickyCol2Width + stickyCol3Width;
- jQuery(_uiNodeCont).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(_uiNodeCont).doubleScroll()
- jQuery(_uiNodeCont).prev('.doubleScroll-scroll-wrapper').css({float: 'right', display:'block'})
- } else {
- jQuery(_uiNodeCont).prev('.doubleScroll-scroll-wrapper').css({display:'none'})
- }
- }
- 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.initialRender = function() {
- _uiNode$Table = $('<table class="AjaxTable table table-striped table-hover table-bordered table-condensed"></table>').appendTo(_uiNodeCont);
- _head = $('<thead></thead>').prependTo(_uiNode$Table);
- _headSort = $('<tr class="sort tblAjax__head__sort"></tr>').prependTo(_head);
- _headFilter = $('<tr class="filter tblAjax__head__filter"></tr>').appendTo(_head);
- _bodyNode = $('<tbody></tbody>').insertAfter(_head);
- $('<tfoot></tfoot>').insertAfter(_bodyNode);
- _foot = $('<div class="foot tblAjax__footer"></div>').insertAfter(_uiNodeCont);
- var footToolbar = $('<div class="btn-toolbar tblAjax__footer__toolbar"></div>').appendTo(_foot);
- $('<span class="tblAjax__footer__toolbar__info"></span>').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 topWrapLeft = document.createElement('div')
- var topWrapRight = document.createElement('div')
- topWrap.appendChild(topWrapLeft)
- topWrap.appendChild(topWrapRight)
- topWrapLeft.style.width = '' + priv.getStickyColsSumWidth() + 'px'
- topWrapLeft.style.padding = '4px'
- topWrapLeft.style.float = 'left'
- topWrapLeft.style.fontSize = '12px'
- topWrapLeft.style.lineHeight = '22px'
- topWrapRight.style.float = 'left'
- topWrapRight.style.padding = '4px'
- topWrapLeft.appendChild(_uiNodeSelectedInfo)
- topWrapRight.appendChild(_uiNodeSpecialFilters)
- _uiNodeCont.parentNode.insertBefore(topWrap, _uiNodeCont)
- priv.renderInlineEditBox();// .tblAjax__inlineEditBox
- _foot = undefined;
- _head = undefined;
- _body = undefined;
- _headSort = undefined;
- _headFilter = undefined;// TODO: refactor
- };
- 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) {
- _uiNode$Table.find('tbody').remove();
- _bodyNode = $('<tbody></tbody>').insertAfter(_head);
- // find out what rows to show next...
- var rowsAdded = 0;
- // slice out the chunk of data we need and create rows
- $.each(_data.rows, function(index, props) {
- var rowNode = priv.renderRow(props);
- if (rowNode) rowNode.appendTo(_bodyNode);
- rowsAdded++;
- if (rowsAdded >= priv.options.pageSize) { // enough rows created
- return false;
- }
- });
- if (_state.page == 1) {
- _totalPages = Math.ceil(_data.total / priv.options.pageSize);
- }
- if (_state.page == _totalPages) { // pad with empty rows if we're at last page.
- while (rowsAdded < priv.options.pageSize) {
- var rowNode = priv.renderRowEmptyNode();
- if (rowNode) rowNode.appendTo(_bodyNode);
- rowsAdded++;
- }
- }
- }
- if (!_foot) {
- priv.renderTableTfoot();
- priv.renderFooter();
- }
- _foot = $(_uiNodeCont).next('.foot');
- var stickyCol1Width = priv.getStickyCol1Width();
- var stickyCol2Width = priv.getStickyCol2Width();
- var stickyCol3Width = priv.getStickyCol3Width();
- if (undefined === _tableWidth) {
- _tableWidth = true;
- var contW = jQuery(_uiNodeCont).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;
- jQuery(_uiNodeCont).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',
- });
- //_uiNode$Table.find('.filter').find('.stickyCol1').css({height:'34px'});
- var sortStickyColHeight = _uiNode$Table.find('.sort').find('th:last').outerHeight();
- _uiNode$Table.find('.sort').find('.stickyCol').css({height: sortStickyColHeight + 'px'});
- 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',
- });
- 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 null; // 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 _formatByValue = _.get(_fieldProps, 'formatByValue', null);
- var _aliasMap = _.get(_fieldProps, 'aliasMap', null);
- return function(val, fieldPK, row) {
- if (_formatByValue && val in _formatByValue) {
- val = p5Utils__format(_formatByValue[val], [val])
- // console.log('p5:string value', val, '_aliasMap', _aliasMap)
- if (_aliasMap) {
- Object.keys(_aliasMap).map(function (mapKey) {
- var mapField = _aliasMap[mapKey]
- if (undefined !== row[mapField]) {
- val = val.replace(new RegExp('\{' + mapKey + '\}', 'g'), row[mapField]);
- }
- })
- }
- }
- return val;
- }
- }(fldName, fieldProps));
- break;
- case "p5:www_link":// @return Element
- 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);
- 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 "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>'),
- rowPK = (_state.primaryKey in props) ? props[_state.primaryKey] : null,
- cellNode,
- columnName, columnProps, val, cellCnt, format, showTooltip, fldWidgetNode,
- 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>'),
- keys = Object.keys(rowFunctions),
- total = keys.length,
- moreFuncBtnNode,
- moreFunctions = [],
- 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) {
- var funObj = rowFunctions[key],
- 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);
- });
- if (3 === priv.options.namespace.split('/').length) { // if namesapce is AntAcl [ and has ref fields or back ref ]
- var funcItemNode = $('<li></li>').appendTo(funcListNode)
- var funObj = {
- ico: 'glyphicon glyphicon-random',
- label: '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 })
- 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 > 0) {
- 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);
- }
- });
- } else {
- popoverCellContent = '<p class="text-muted">Brak dodatkowych funkcji</p>';
- }
- //_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);
- // ReactDOM.render(
- // h(P5UI__TableAjaxRowCheckbox, {
- // disabled: true,
- // primaryKey: 'empty',
- // store: priv.options.selectedStore,
- // actions: priv.options.selectedActions
- // }),
- // cellNode.get(0)
- // );
- }
- 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() {
- var nodeClass = 'tblAjax__' + 'head__sort'
- var currentNode = _uiNode$Table.find('thead').find('.' + nodeClass)
- var node = $('<tr class="sort ' + nodeClass + '"></tr>')
- if (priv.options.tblFunctions || priv.options.filtersClean) {
- var headCell = $('<th class="text-right head-info stickyCol stickyCol1"></th>').appendTo(node)
- $.map(priv.options.tblFunctions, function (funObj, funName) {
- var funHtml = $('<a></a>')
- funHtml.attr('href', funObj.href || '#')
- if (funObj.title) funHtml.attr('title', funObj.title)
- if (funObj.icon) funHtml.html('<span class="glyphicon glyphicon-' + funObj.icon + '"></span> ')
- if (funObj.method && priv[funObj.method] && typeof priv[funObj.method] == 'function') {
- funHtml.on('click', priv[funObj.method])
- }
- funHtml.appendTo(headCell)
- })
- }
- if (_state.primaryKey && priv.options.checkboxes) {
- var headCell = $('<th class="stickyCol stickyCol2" style="padding:3px 5px"></th>').appendTo(node);
- ReactDOM.render(
- h(P5UI__TableAjaxRowCheckbox, {
- namespace: priv.options.namespace,
- primaryKey: 'select-all',
- store: priv.options.selectedStore,
- actions: priv.options.selectedActions
- }),
- headCell.get(0)
- );
- }
- for (var i = 0; i < _state.colsSorted.length; i++) {
- var column = _state.colsSorted[i]
- var props = _data.cols[column]
- if (props.hidden) continue
- var headCell = $('<th class="ta-ordering"></th>').appendTo(node)
- if (i == 1) headCell.addClass('stickyCol stickyCol3')
- // DBG && console.log('DBG: render header cell action order by', { column, props }); // TODO: DBG isSrotable
- if (props.type != 'special' && props.type != 'geom' && props.type != "simpleLink" && props.type != "ref") { // TODO: props.isSortable
- headCell.on('click', {column: column}, priv.columnClicked)
- }
- var nodeLabel = (props.friendly) ? props.friendly : column
- var nodeTitle = column
- if (props.description && props.description.length > 0) {
- nodeTitle = p5Utils__format("{0} ({1})", [props.description, column])
- }
- else if (props._tsRetId > 0) {
- nodeTitle = p5Utils__format("Kliknij na pole i przejdź do powiązanych rekordów ({0})", [nodeTitle])
- }
- if ('ref' === props.type && props.xsdRefType) {
- nodeLabel = '<i class="glyphicon glyphicon-export"></i> ' + props.xsdRefType
- if (props.description && props.description.length > 0 && props.description !== column) {
- nodeTitle = p5Utils__format("{0} (ref {1})", [props.description, column])
- } else {
- nodeTitle = p5Utils__format("(ref {0})", [column])
- }
- }
- var headCnt = $(p5Utils__format('<span class="pull-left" title="{1}">{0}</span>', [nodeLabel, nodeTitle]))
- headCnt.appendTo(headCell)
- if (column == _state._currSortCol) {
- headCell.addClass((_state._currSortFlip) ? 'ta-ordering-down' : 'ta-ordering-up')
- }
- if (column !== _state.primaryKey) {
- var hideColBtn = $('<i class="glyphicon glyphicon-remove remove-cell"></i>')
- hideColBtn.on('click', {column: column}, priv.columnHideClicked)
- hideColBtn.appendTo(headCell)
- }
- }
- currentNode.replaceWith(node)
- };
- 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() {
- var nodeClass = 'tblAjax__' + 'head__filter',
- currentNode = _uiNode$Table.find('thead').find('.' + nodeClass),
- node;
- // currentNode.find('i').tooltip('hide');
- node = $('<tr class="filter ' + nodeClass + '"></tr>');
- //_head.find(".filter").remove();
- //_headFilter = $('<tr class="filter"></tr>').appendTo(_head);
- var headCell;
- var elem;
- var placeHolder = '';
- var tooltip = '';
- //create the functions column
- if (priv.options.rowFunctions || priv.options.filtersClean) {
- var headCell = $('<th class="text-right stickyCol stickyCol1"></th>').appendTo(node);
- headCell.css({padding: '0'});
- if (priv.options.filtersClean) {
- ReactDOM.render(
- h(p5UI__TableAjaxClearAllFilters, {
- store: priv.options.filterStore,
- actions: priv.options.filterActions
- }),
- headCell.get(0)
- );
- }
- }
- //create the filter checkbox
- if (_state.primaryKey && priv.options.checkboxes) {
- // tooltip = priv.options.types.bool.filterTooltip || 'Pokaż tylko:<br/>nieokreślony,<br/>zaznaczony,<br/>niezaznaczony';
- headCell = $('<th class="stickyCol stickyCol2" style="padding:0"></th>').appendTo(node);
- ReactDOM.render(
- h(P5UI__TableAjaxFieldCheckboxSearch, {
- namespace: priv.options.namespace,
- fieldName: ( priv.options.checkboxIdContext ? '@sel_' + priv.options.checkboxIdContext : '@selected' ),
- store: priv.options.filterStore,
- actions: priv.options.filterActions
- }),
- headCell.get(0)
- );
- }
- //create the column filters
- for (var i = 0; i < _state.colsSorted.length; i++) {
- var column = _state.colsSorted[i];
- var props = _data.cols[column];
- tooltip = props.filterTooltip === true ? undefined : props.filterTooltip === false ? '' : props.filterTooltip;
- placeHolder = props.placeHolder === true ? undefined : props.placeHolder === false ? '' : props.placeHolder;
- if (props.hidden) continue;
- headCell = $('<th></th>').appendTo(node);
- headCell.css({padding: '0'});
- if (i == 1) headCell.addClass('stickyCol stickyCol3');
- ReactDOM.render(
- h(p5UI__FieldInputFilterSearch, {
- disabled: (priv.options.forceFilterInit && undefined !== priv.options.forceFilterInit[column]),
- fieldName: column,
- type: props.type,
- lagacyProps: props, // TODO: use ony required like xsdType
- // xsdType: props.xsdType,
- store: priv.options.filterStore,
- onChange: function (fieldName, value) {
- priv.options.filterStore.dispatch( priv.options.filterActions.delayFilter(fieldName, value) );
- }
- }),
- headCell.get(0)
- );
- }
- currentNode.replaceWith(node);
- };
- priv.renderTableTfoot = function() {
- _uiNode$Table.find('tfoot').remove();
- _foot = $('<tfoot></tfoot>').insertAfter(_bodyNode);
- //$(_uiNodeCont).next('.foot').replaceWith(_foot);
- };
- priv.renderFooter = function() {
- priv.renderFooterInfo();
- priv.renderFooterPagination();
- priv.renderFooterPageSizes();
- priv.renderFooterColumnPicker();
- priv.renderFooterFunctions();
- priv.renderFooterExport();
- };
- priv.renderFooterInfo = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__info',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
- node = $('<div class="foot-info ' + nodeClass + '"></div>');
- var fromRow = Math.max(_state.page - 1, 0) * _state.pageSize;
- var total = _data.total;
- var toRow = Math.min(fromRow + _state.pageSize, total);
- if (_data.total > 0) {
- $(p5Utils__format('<p>Wiersze od {0} do {1} z {2}</p>', [fromRow + 1, toRow, total])).appendTo(node);
- } else {
- $('<p>Brak wierszy pasujących do kryteriów wyszukiwania</p>').appendTo(node);
- }
- currentNode.replaceWith(node);
- };
- priv.renderFooterPagination = function() {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__pagination',
- currentNode = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- var currPage = _state.page;
- var totalPages = Math.ceil(_data.total / _state.pageSize);
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass, '_data.total', _data.total, 'currPage', currPage);
- if (_data.total > 0) {
- node = $('<div class="btn-group ' + nodeClass + '"></div>');
- 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;
- //$(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>', [currPage == totalPages ? ' 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>', [currPage == totalPages ? ' 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 = $(_uiNodeCont).next('.foot').find('.' + nodeClass),
- node;
- if (priv.options.debug || DBG) console.log('Render: ', nodeClass);
- if (_data.total > 0 && 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 = $(_uiNodeCont).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 = $(_uiNodeCont).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 = $(_uiNodeCont).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>').appendTo(ul);
- $('<a href="index.php" target="_blank" class=""><i class="glyphicon glyphicon-share"></i>Export do HTML</a>').appendTo(li);
- li.on('click', 'a', priv.exportToHTML);
- var 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);
- var 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);
- } else {
- node = $('<span class="' + nodeClass + '"></span>');
- }
- currentNode.replaceWith(node);
- };
- priv.renderInlineEditBox = function() {
- var nodeClass = 'tblAjax__' + 'inlineEditBox',
- currentNode = $(_uiNodeCont).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 = $(_uiNodeCont).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.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;
- }
- }
- var exportUrl = 'index.php?_route=ViewTableAjax&_task=export&namespace=' + priv.options.namespace;
- exportUrl += '&format=' + format;
- exportUrl += '&flds=' + exportFields.join(',');
- exportUrl += '&sortCol=' + (_state._currSortCol || '');
- exportUrl += '&sortDir=' + (_state._currSortFlip ? "desc" : "asc");
- exportUrl += (_state._filterQuery) ? "&" + _state._filterQuery : "";
- exportUrl += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
- exportUrl += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
- node.attr('href', exportUrl);
- };
- 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(_uiNodeCont).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 = '';
- initUrlAdd += '&currSortCol=' + _state._currSortCol;
- initUrlAdd += '&currSortFlip=' + ( _state._currSortCol ? "desc" : "asc" );
- DBG && console.warn('DBG:update... - FETCH_DATA', { '_state._filterQuery': _state._filterQuery, '_state._specialFilterQuery': _state._specialFilterQuery, _state });
- initUrlAdd += (_state._filterQuery) ? "&" + _state._filterQuery : "";
- initUrlAdd += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
- initUrlAdd += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
- // 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 });
- priv.setState(state);
- 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);
- renderParts['head'] = true;
- } 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(_uiNodeCont).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(_uiNodeCont).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;
- //we might have more/less data now. Recalculate stuff.
- if (_state.page > 1) {
- _totalPages = Math.ceil(_data.total / priv.options.pageSize);
- }
- };
- /*
- 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(_uiNodeCont).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(_uiNodeCont).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(_uiNodeCont).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 (e.data.pageIndex < 1 || e.data.pageIndex > totalPages) return;
- //set the new page
- _state.page = 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(_uiNodeCont).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(_uiNodeCont).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(_uiNodeCont).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(_uiNodeCont).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(_uiNodeCont).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 = $(_uiNodeCont).next('.foot').find('.' + nodeClass)
- ;
- currentNode.find('input[type="radio"]').prop("checked", false);
- };
- priv.modelColFilter_uiCheckColFilter = function(filterKey) {
- var nodeClass = 'tblAjax__' + 'footer__toolbar__columnPicker',
- currentNode = $(_uiNodeCont).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(_uiNodeCont).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(_uiNodeCont).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(_uiNodeCont).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) {
- var inlineEditBox$Node = $(_uiNodeCont).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.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);
- urlAdd += '&currSortCol=' + (_state._currSortCol || '');
- urlAdd += '&currSortFlip=' + (_state._currSortFlip ? "desc" : "asc");
- // TODO: compare with filterStore
- DBG && console.log('DBG::loadPage... FETCH_DATA', { '_state._filterQuery': _state._filterQuery, '_state._specialFilterQuery': _state._specialFilterQuery, _state });
- urlAdd += (_state._filterQuery) ? "&" + _state._filterQuery : "";
- urlAdd += (_state._specialFilterQuery) ? "&" + _state._specialFilterQuery : "";
- urlAdd += (_state._forceFilterQuery) ? "&" + _state._forceFilterQuery : "";
- _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 });
- priv.setState(state);
- _uiNode$Table.parent().parent().removeClass('AjaxTable-loading');
- } 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.id = 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();
- });
- };
|