From 316d211b99fa1e11b5d7b2a8b9a04a405fba3202 Mon Sep 17 00:00:00 2001 From: Harry Bomrah Date: Wed, 18 Nov 2015 23:51:49 +0800 Subject: [PATCH] updates for universal table. Added filtering, reordering, sorting and categorizable --- .../universal_table/jquery-ui.min.js | 7 ++ .../universal_table/universal-table.scss | 17 +++ .../admin/universal_tables_controller.rb | 33 ++++- .../universal_tables_controller.rb | 116 +++++++++++++++--- app/helpers/admin/universal_tables_helper.rb | 31 +++++ .../universal_table/application_helper.rb | 4 - app/models/table_column.rb | 2 + app/models/u_table.rb | 1 + .../admin/universal_tables/_column.html.erb | 27 ++-- .../universal_tables/_date_field.html.erb | 3 +- .../universal_tables/_period_field.html.erb | 6 +- .../universal_tables/_table_form.html.erb | 30 ++++- .../universal_tables/_text_field.html.erb | 18 ++- .../admin/universal_tables/show.html.erb | 19 +-- config/locales/zh_tw.yml | 2 +- 15 files changed, 269 insertions(+), 47 deletions(-) create mode 100644 app/assets/javascripts/universal_table/jquery-ui.min.js create mode 100644 app/helpers/admin/universal_tables_helper.rb delete mode 100644 app/helpers/universal_table/application_helper.rb diff --git a/app/assets/javascripts/universal_table/jquery-ui.min.js b/app/assets/javascripts/universal_table/jquery-ui.min.js new file mode 100644 index 0000000..8475a32 --- /dev/null +++ b/app/assets/javascripts/universal_table/jquery-ui.min.js @@ -0,0 +1,7 @@ +/*! jQuery UI - v1.11.4 - 2015-11-18 +* http://jqueryui.com +* Includes: core.js, widget.js, mouse.js, sortable.js +* Copyright jQuery Foundation and other contributors; Licensed MIT */ + +(function(e){"function"==typeof define&&define.amd?define(["jquery"],e):e(jQuery)})(function(e){function t(t,s){var n,a,o,r=t.nodeName.toLowerCase();return"area"===r?(n=t.parentNode,a=n.name,t.href&&a&&"map"===n.nodeName.toLowerCase()?(o=e("img[usemap='#"+a+"']")[0],!!o&&i(o)):!1):(/^(input|select|textarea|button|object)$/.test(r)?!t.disabled:"a"===r?t.href||s:s)&&i(t)}function i(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}e.ui=e.ui||{},e.extend(e.ui,{version:"1.11.4",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({scrollParent:function(t){var i=this.css("position"),s="absolute"===i,n=t?/(auto|scroll|hidden)/:/(auto|scroll)/,a=this.parents().filter(function(){var t=e(this);return s&&"static"===t.css("position")?!1:n.test(t.css("overflow")+t.css("overflow-y")+t.css("overflow-x"))}).eq(0);return"fixed"!==i&&a.length?a:e(this[0].ownerDocument||document)},uniqueId:function(){var e=0;return function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++e)})}}(),removeUniqueId:function(){return this.each(function(){/^ui-id-\d+$/.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(i){return t(i,!isNaN(e.attr(i,"tabindex")))},tabbable:function(i){var s=e.attr(i,"tabindex"),n=isNaN(s);return(n||s>=0)&&t(i,!n)}}),e("").outerWidth(1).jquery||e.each(["Width","Height"],function(t,i){function s(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===i?["Left","Right"]:["Top","Bottom"],a=i.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+i]=function(t){return void 0===t?o["inner"+i].call(this):this.each(function(){e(this).css(a,s(this,t)+"px")})},e.fn["outer"+i]=function(t,n){return"number"!=typeof t?o["outer"+i].call(this,t):this.each(function(){e(this).css(a,s(this,t,!0,n)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),disableSelection:function(){var e="onselectstart"in document.createElement("div")?"selectstart":"mousedown";return function(){return this.bind(e+".ui-disableSelection",function(e){e.preventDefault()})}}(),enableSelection:function(){return this.unbind(".ui-disableSelection")},zIndex:function(t){if(void 0!==t)return this.css("zIndex",t);if(this.length)for(var i,s,n=e(this[0]);n.length&&n[0]!==document;){if(i=n.css("position"),("absolute"===i||"relative"===i||"fixed"===i)&&(s=parseInt(n.css("zIndex"),10),!isNaN(s)&&0!==s))return s;n=n.parent()}return 0}}),e.ui.plugin={add:function(t,i,s){var n,a=e.ui[t].prototype;for(n in s)a.plugins[n]=a.plugins[n]||[],a.plugins[n].push([i,s[n]])},call:function(e,t,i,s){var n,a=e.plugins[t];if(a&&(s||e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType))for(n=0;a.length>n;n++)e.options[a[n][0]]&&a[n][1].apply(e.element,i)}};var s=0,n=Array.prototype.slice;e.cleanData=function(t){return function(i){var s,n,a;for(a=0;null!=(n=i[a]);a++)try{s=e._data(n,"events"),s&&s.remove&&e(n).triggerHandler("remove")}catch(o){}t(i)}}(e.cleanData),e.widget=function(t,i,s){var n,a,o,r,h={},l=t.split(".")[0];return t=t.split(".")[1],n=l+"-"+t,s||(s=i,i=e.Widget),e.expr[":"][n.toLowerCase()]=function(t){return!!e.data(t,n)},e[l]=e[l]||{},a=e[l][t],o=e[l][t]=function(e,t){return this._createWidget?(arguments.length&&this._createWidget(e,t),void 0):new o(e,t)},e.extend(o,a,{version:s.version,_proto:e.extend({},s),_childConstructors:[]}),r=new i,r.options=e.widget.extend({},r.options),e.each(s,function(t,s){return e.isFunction(s)?(h[t]=function(){var e=function(){return i.prototype[t].apply(this,arguments)},n=function(e){return i.prototype[t].apply(this,e)};return function(){var t,i=this._super,a=this._superApply;return this._super=e,this._superApply=n,t=s.apply(this,arguments),this._super=i,this._superApply=a,t}}(),void 0):(h[t]=s,void 0)}),o.prototype=e.widget.extend(r,{widgetEventPrefix:a?r.widgetEventPrefix||t:t},h,{constructor:o,namespace:l,widgetName:t,widgetFullName:n}),a?(e.each(a._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete a._childConstructors):i._childConstructors.push(o),e.widget.bridge(t,o),o},e.widget.extend=function(t){for(var i,s,a=n.call(arguments,1),o=0,r=a.length;r>o;o++)for(i in a[o])s=a[o][i],a[o].hasOwnProperty(i)&&void 0!==s&&(t[i]=e.isPlainObject(s)?e.isPlainObject(t[i])?e.widget.extend({},t[i],s):e.widget.extend({},s):s);return t},e.widget.bridge=function(t,i){var s=i.prototype.widgetFullName||t;e.fn[t]=function(a){var o="string"==typeof a,r=n.call(arguments,1),h=this;return o?this.each(function(){var i,n=e.data(this,s);return"instance"===a?(h=n,!1):n?e.isFunction(n[a])&&"_"!==a.charAt(0)?(i=n[a].apply(n,r),i!==n&&void 0!==i?(h=i&&i.jquery?h.pushStack(i.get()):i,!1):void 0):e.error("no such method '"+a+"' for "+t+" widget instance"):e.error("cannot call methods on "+t+" prior to initialization; "+"attempted to call method '"+a+"'")}):(r.length&&(a=e.widget.extend.apply(null,[a].concat(r))),this.each(function(){var t=e.data(this,s);t?(t.option(a||{}),t._init&&t._init()):e.data(this,s,new i(a,this))})),h}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"
",options:{disabled:!1,create:null},_createWidget:function(t,i){i=e(i||this.defaultElement||this)[0],this.element=e(i),this.uuid=s++,this.eventNamespace="."+this.widgetName+this.uuid,this.bindings=e(),this.hoverable=e(),this.focusable=e(),i!==this&&(e.data(i,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===i&&this.destroy()}}),this.document=e(i.style?i.ownerDocument:i.document||i),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(t,i){var s,n,a,o=t;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof t)if(o={},s=t.split("."),t=s.shift(),s.length){for(n=o[t]=e.widget.extend({},this.options[t]),a=0;s.length-1>a;a++)n[s[a]]=n[s[a]]||{},n=n[s[a]];if(t=s.pop(),1===arguments.length)return void 0===n[t]?null:n[t];n[t]=i}else{if(1===arguments.length)return void 0===this.options[t]?null:this.options[t];o[t]=i}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled",!!t),t&&(this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus"))),this},enable:function(){return this._setOptions({disabled:!1})},disable:function(){return this._setOptions({disabled:!0})},_on:function(t,i,s){var n,a=this;"boolean"!=typeof t&&(s=i,i=t,t=!1),s?(i=n=e(i),this.bindings=this.bindings.add(i)):(s=i,i=this.element,n=this.widget()),e.each(s,function(s,o){function r(){return t||a.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?a[o]:o).apply(a,arguments):void 0}"string"!=typeof o&&(r.guid=o.guid=o.guid||r.guid||e.guid++);var h=s.match(/^([\w:-]*)\s*(.*)$/),l=h[1]+a.eventNamespace,u=h[2];u?n.delegate(u,l,r):i.bind(l,r)})},_off:function(t,i){i=(i||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,t.unbind(i).undelegate(i),this.bindings=e(this.bindings.not(t).get()),this.focusable=e(this.focusable.not(t).get()),this.hoverable=e(this.hoverable.not(t).get())},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,o=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(o)&&o.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var o,r=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),o=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),o&&e.effects&&e.effects.effect[r]?s[t](n):r!==t&&s[r]?s[r](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}}),e.widget;var a=!1;e(document).mouseup(function(){a=!1}),e.widget("ui.mouse",{version:"1.11.4",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(i){return!0===e.data(i.target,t.widgetName+".preventClickEvent")?(e.removeData(i.target,t.widgetName+".preventClickEvent"),i.stopImmediatePropagation(),!1):void 0}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){if(!a){this._mouseMoved=!1,this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var i=this,s=1===t.which,n="string"==typeof this.options.cancel&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;return s&&!n&&this._mouseCapture(t)?(this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){i.mouseDelayMet=!0},this.options.delay)),this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(t)!==!1,!this._mouseStarted)?(t.preventDefault(),!0):(!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return i._mouseMove(e)},this._mouseUpDelegate=function(e){return i._mouseUp(e)},this.document.bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),a=!0,!0)):!0}},_mouseMove:function(t){if(this._mouseMoved){if(e.ui.ie&&(!document.documentMode||9>document.documentMode)&&!t.button)return this._mouseUp(t);if(!t.which)return this._mouseUp(t)}return(t.which||t.button)&&(this._mouseMoved=!0),this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){return this.document.unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),a=!1,!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}}),e.widget("ui.sortable",e.ui.mouse,{version:"1.11.4",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_isOverAxis:function(e,t,i){return e>=t&&t+i>e},_isFloating:function(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))},_create:function(){this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.offset=this.element.offset(),this._mouseInit(),this._setHandleClassName(),this.ready=!0},_setOption:function(e,t){this._super(e,t),"handle"===e&&this._setHandleClassName()},_setHandleClassName:function(){this.element.find(".ui-sortable-handle").removeClass("ui-sortable-handle"),e.each(this.items,function(){(this.instance.options.handle?this.item.find(this.instance.options.handle):this.item).addClass("ui-sortable-handle")})},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled").find(".ui-sortable-handle").removeClass("ui-sortable-handle"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_mouseCapture:function(t,i){var s=null,n=!1,a=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(t),e(t.target).parents().each(function(){return e.data(this,a.widgetName+"-item")===a?(s=e(this),!1):void 0}),e.data(t.target,a.widgetName+"-item")===a&&(s=e(t.target)),s?!this.options.handle||i||(e(this.options.handle,s).find("*").addBack().each(function(){this===t.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(t,i,s){var n,a,o=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(a=this.document.find("body"),this.storedCursor=a.css("cursor"),a.css("cursor",o.cursor),this.storedStylesheet=e("").appendTo(a)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var i,s,n,a,o=this.options,r=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==this.document[0]&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY=0;i--)if(s=this.items[i],n=s.item[0],a=this._intersectsWithPointer(s),a&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===a?"next":"prev"]()[0]!==n&&!e.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],n):!0)){if(this.direction=1===a?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(t,s),this._trigger("change",t,this._uiHash());break}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,i){if(t){if(e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t),this.options.revert){var s=this,n=this.placeholder.offset(),a=this.options.axis,o={};a&&"x"!==a||(o.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollLeft)),a&&"y"!==a||(o.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===this.document[0].body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,e(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){s._clear(t)})}else this._clear(t,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},e(i).each(function(){var i=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);i&&s.push((t.key||i[1]+"[]")+"="+(t.key&&t.expression?i[1]:i[2]))}),!s.length&&t.key&&s.push(t.key+"="),s.join("&")},toArray:function(t){var i=this._getItemsAsjQuery(t&&t.connected),s=[];return t=t||{},i.each(function(){s.push(e(t.item||this).attr(t.attribute||"id")||"")}),s},_intersectsWith:function(e){var t=this.positionAbs.left,i=t+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,a=e.left,o=a+e.width,r=e.top,h=r+e.height,l=this.offset.click.top,u=this.offset.click.left,d="x"===this.options.axis||s+l>r&&h>s+l,c="y"===this.options.axis||t+u>a&&o>t+u,p=d&&c;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?p:t+this.helperProportions.width/2>a&&o>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(e){var t="x"===this.options.axis||this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),i="y"===this.options.axis||this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),s=t&&i,n=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return s?this.floating?a&&"right"===a||"down"===n?2:1:n&&("down"===n?2:1):!1},_intersectsWithSides:function(e){var t=this._isOverAxis(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),i=this._isOverAxis(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),s=this._getDragVerticalDirection(),n=this._getDragHorizontalDirection();return this.floating&&n?"right"===n&&i||"left"===n&&!i:s&&("down"===s&&t||"up"===s&&!t)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this._setHandleClassName(),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){function i(){r.push(this)}var s,n,a,o,r=[],h=[],l=this._connectWith();if(l&&t)for(s=l.length-1;s>=0;s--)for(a=e(l[s],this.document[0]),n=a.length-1;n>=0;n--)o=e.data(a[n],this.widgetFullName),o&&o!==this&&!o.options.disabled&&h.push([e.isFunction(o.options.items)?o.options.items.call(o.element):e(o.options.items,o.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),o]);for(h.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),s=h.length-1;s>=0;s--)h[s][0].each(i);return e(r)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var i=0;t.length>i;i++)if(t[i]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var i,s,n,a,o,r,h,l,u=this.items,d=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],c=this._connectWith();if(c&&this.ready)for(i=c.length-1;i>=0;i--)for(n=e(c[i],this.document[0]),s=n.length-1;s>=0;s--)a=e.data(n[s],this.widgetFullName),a&&a!==this&&!a.options.disabled&&(d.push([e.isFunction(a.options.items)?a.options.items.call(a.element[0],t,{item:this.currentItem}):e(a.options.items,a.element),a]),this.containers.push(a));for(i=d.length-1;i>=0;i--)for(o=d[i][1],r=d[i][0],s=0,l=r.length;l>s;s++)h=e(r[s]),h.data(this.widgetName+"-item",o),u.push({item:h,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(t){this.floating=this.items.length?"x"===this.options.axis||this._isFloating(this.items[0].item):!1,this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,a;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?e(this.options.toleranceElement,s.item):s.item,t||(s.width=n.outerWidth(),s.height=n.outerHeight()),a=n.offset(),s.left=a.left,s.top=a.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)a=this.containers[i].element.offset(),this.containers[i].containerCache.left=a.left,this.containers[i].containerCache.top=a.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(t){t=t||this;var i,s=t.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=t.currentItem[0].nodeName.toLowerCase(),n=e("<"+s+">",t.document[0]).addClass(i||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tbody"===s?t._createTrPlaceholder(t.currentItem.find("tr").eq(0),e("",t.document[0]).appendTo(n)):"tr"===s?t._createTrPlaceholder(t.currentItem,n):"img"===s&&n.attr("src",t.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(e,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10)))}}),t.placeholder=e(s.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),s.placeholder.update(t,t.placeholder)},_createTrPlaceholder:function(t,i){var s=this;t.children().each(function(){e(" ",s.document[0]).attr("colspan",e(this).attr("colspan")||1).appendTo(i)})},_contactContainers:function(t){var i,s,n,a,o,r,h,l,u,d,c=null,p=null;for(i=this.containers.length-1;i>=0;i--)if(!e.contains(this.currentItem[0],this.containers[i].element[0]))if(this._intersectsWith(this.containers[i].containerCache)){if(c&&e.contains(this.containers[i].element[0],c.element[0]))continue;c=this.containers[i],p=i}else this.containers[i].containerCache.over&&(this.containers[i]._trigger("out",t,this._uiHash(this)),this.containers[i].containerCache.over=0);if(c)if(1===this.containers.length)this.containers[p].containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1);else{for(n=1e4,a=null,u=c.floating||this._isFloating(this.currentItem),o=u?"left":"top",r=u?"width":"height",d=u?"clientX":"clientY",s=this.items.length-1;s>=0;s--)e.contains(this.containers[p].element[0],this.items[s].item[0])&&this.items[s].item[0]!==this.currentItem[0]&&(h=this.items[s].item.offset()[o],l=!1,t[d]-h>this.items[s][r]/2&&(l=!0),n>Math.abs(t[d]-h)&&(n=Math.abs(t[d]-h),a=this.items[s],this.direction=l?"up":"down"));if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[p])return this.currentContainer.containerCache.over||(this.containers[p]._trigger("over",t,this._uiHash()),this.currentContainer.containerCache.over=1),void 0;a?this._rearrange(t,a,null,!0):this._rearrange(t,null,this.containers[p].element,!0),this._trigger("change",t,this._uiHash()),this.containers[p]._trigger("change",t,this._uiHash(this)),this.currentContainer=this.containers[p],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[p]._trigger("over",t,this._uiHash(this)),this.containers[p].containerCache.over=1}},_createHelper:function(t){var i=this.options,s=e.isFunction(i.helper)?e(i.helper.apply(this.element[0],[t,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||e("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==this.document[0]&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===this.document[0].body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,"document"===n.containment?this.document.width():this.window.width()-this.helperProportions.width-this.margins.left,("document"===n.containment?this.document.width():this.window.height()||this.document[0].body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(t=e(n.containment)[0],i=e(n.containment).offset(),s="hidden"!==e(t).css("overflow"),this.containment=[i.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]) +},_convertPositionTo:function(t,i){i||(i=this.position);var s="absolute"===t?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():a?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():a?0:n.scrollLeft())*s}},_generatePosition:function(t){var i,s,n=this.options,a=t.pageX,o=t.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==this.document[0]&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.leftthis.containment[2]&&(a=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1],o=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((a-this.originalPageX)/n.grid[0])*n.grid[0],a=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(e,t,i,s){i?i[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(e,t){function i(e,t,i){return function(s){i._trigger(e,s,t._uiHash(t))}}this.reverting=!1;var s,n=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(s in this._storedCSS)("auto"===this._storedCSS[s]||"static"===this._storedCSS[s])&&(this._storedCSS[s]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!t&&n.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||n.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(t||(n.push(function(e){this._trigger("remove",e,this._uiHash())}),n.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),n.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),s=this.containers.length-1;s>=0;s--)t||n.push(i("deactivate",this,this.containers[s])),this.containers[s].containerCache.over&&(n.push(i("out",this,this.containers[s])),this.containers[s].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,t||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.cancelHelperRemoval||(this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null),!t){for(s=0;n.length>s;s++)n[s].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!this.cancelHelperRemoval},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var i=t||this;return{helper:i.helper,placeholder:i.placeholder||e([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:t?t.element:null}}})}); \ No newline at end of file diff --git a/app/assets/stylesheets/universal_table/universal-table.scss b/app/assets/stylesheets/universal_table/universal-table.scss index 845708c..6c39be0 100644 --- a/app/assets/stylesheets/universal_table/universal-table.scss +++ b/app/assets/stylesheets/universal_table/universal-table.scss @@ -29,6 +29,16 @@ &:nth-child(even) { background-color: #e8e8e8; } + &:nth-child(odd) { + background-color: #fff; + } + .draggable { + cursor: move; + } + .draggable i{ + cursor: move; + vertical-align: middle; + } } } .attributes-checkbox { @@ -49,6 +59,13 @@ -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; + .select-holder{ + margin-left: 20px; + display: inline-block; + span { + margin: 0 5px; + } + } } .main-forms fieldset .input-area:after { diff --git a/app/controllers/admin/universal_tables_controller.rb b/app/controllers/admin/universal_tables_controller.rb index e231d0e..b35bb3e 100644 --- a/app/controllers/admin/universal_tables_controller.rb +++ b/app/controllers/admin/universal_tables_controller.rb @@ -6,7 +6,6 @@ class Admin::UniversalTablesController < OrbitAdminController .order_by(sort) .with_categories(filters("category")) - @tables = search_data(@tables,[:title]) end def show @@ -15,7 +14,11 @@ class Admin::UniversalTablesController < OrbitAdminController if !@table.nil? @columns = @table.table_columns.asc(:order) @table_fields = @columns.collect{|tc| tc.title} - @entries = @table.table_entries.desc(:created_at).page(params[:page_id]).per(10) + if params[:q].present? + @entries = Kaminari.paginate_array(search_data(@table)).page(params[:page]).per(10) + else + @entries = @table.table_entries.desc(:created_at).page(params[:page]).per(10) + end end end @@ -103,6 +106,24 @@ class Admin::UniversalTablesController < OrbitAdminController private + def search_data(table) + keywords = params["q"] + keywords = keywords.strip.nil? ? keywords : keywords.strip + regexes = keywords.split(/\s+(?=(?:[^"]*"[^"]*")*[^"]*$)/) + regex = Regexp.union(regexes.map{|word| Regexp.new(".*"+word+".*", "i")}) + + column = table.table_columns.where(:type.in => ["text","editor"]) + columns = [] + column.each do |c| + columns = (columns | c.column_entries.any_of(:"text.en" => regex).or(:"text.zh_tw" => regex).or(:"content.en" => regex).or(:"content.zh_tw" => regex)) + end + entries = [] + columns.each do |column| + entries << column.table_entry + end + entries = entries.sort{|k,v| v["created_at"] <=> k["created_at"]} + end + def table_params params.require(:u_table).permit! end @@ -110,4 +131,10 @@ class Admin::UniversalTablesController < OrbitAdminController def table_entry_params params.require(:table_entry).permit! end -end \ No newline at end of file +end + + + + + + diff --git a/app/controllers/universal_tables_controller.rb b/app/controllers/universal_tables_controller.rb index 4607ef1..7e483dd 100644 --- a/app/controllers/universal_tables_controller.rb +++ b/app/controllers/universal_tables_controller.rb @@ -1,19 +1,50 @@ class UniversalTablesController < ApplicationController + include Admin::UniversalTablesHelper def index params = OrbitHelper.params table = UTable.where(:category_id => OrbitHelper.page_categories.first).first rescue nil page = Page.where(:page_id => params[:page_id]).first if !table.nil? + reset = "hide" table_heads = table.table_columns.where(:display_in_index => true).asc(:order).collect do |tc| search = "" - sort = "hide" + sort_class = "sort" + sort = "" + form_field = "" + query_string = "" + query_string = "&column=#{params["column"]}&q=#{params["q"]}" if params["column"].present? + query_string = query_string + "&page_no=#{params["page_no"]}" if params["page_no"].present? + sort_url = "/#{I18n.locale.to_s}#{page.url}?sortcolumn=#{tc.key}&sort=asc#{query_string}" title_class = "" case tc.type - when "date","period","image" + when "date" search = "hide" + when "period","image" + sort_class = "sort hide" + search = "hide" + sort_url = "#" + sort = "hide" + when "editor" + sort_url = "#" + sort = "hide" + sort_class = "sort hide" + when "text" + if tc.make_categorizable + select_values = tc.column_entries.distinct(:text).uniq + form_field = "" + end end - title_class = title_class + "no-sort" if sort == "hide" + if params["sortcolumn"] == tc.key + sort_class = params["sort"] == "asc" ? "sort-desc" : "sort-asc" + sort_url = "/#{I18n.locale.to_s}#{page.url}?sortcolumn=#{tc.key}&sort=#{params["sort"] == "asc" ? "desc" : "asc"}#{query_string}" + end + + title_class = title_class + "no-sort" if sort == "sort" title_class = title_class + " no-search" if search == "hide" { @@ -21,31 +52,79 @@ class UniversalTablesController < ApplicationController "type" => tc.type, "key" => tc.key, "search" => search, + "form-field" => form_field, "sort" => sort, + "sort-class" => sort_class, + "sort-url" => sort_url, "title-class" => title_class } end tablecolumns = table.table_columns.where(:display_in_index => true).asc(:order) rows = [] if params["column"].present? + reset = "" keywords = params["q"] keywords = keywords.strip.nil? ? keywords : keywords.strip regexes = keywords.split(/\s+(?=(?:[^"]*"[^"]*")*[^"]*$)/) regex = Regexp.union(regexes.map{|word| Regexp.new(".*"+word+".*", "i")}) column = table.table_columns.where(:key => params["column"]).first - columns = column.column_entries.any_of(:"text.en" => regex).or(:"text.zh_tw" => regex).or(:"content.en" => regex).or(:"content.zh_tw" => regex) + if params["sort"].present? + column_to_sort = table.table_columns.where(:key => params["sortcolumn"]).first + case column_to_sort.type + when "text" + field_name = :text + when "editor" + field_name = :content + when "date" + field_name = :date + end + if params["column"] == params["sortcolumn"] + columns = column.column_entries.any_of(:"text.en" => regex).or(:"text.zh_tw" => regex).or(:"content.en" => regex).or(:"content.zh_tw" => regex).order_by(field_name => params["sort"]) + else + temp = column.column_entries.any_of(:"text.en" => regex).or(:"text.zh_tw" => regex).or(:"content.en" => regex).or(:"content.zh_tw" => regex) + columns = [] + temp.each do |c| + columns << c.table_entry.column_entries.where(:table_column_id => column_to_sort.id).first + end + sorted_columns = column_to_sort.column_entries.order_by(field_name => params["sort"]).to_a + columns = sorted_columns & columns + end + else + columns = column.column_entries.any_of(:"text.en" => regex).or(:"text.zh_tw" => regex).or(:"content.en" => regex).or(:"content.zh_tw" => regex) + end entries = [] columns.each do |column| entries << column.table_entry end - entries = entries.sort{|k,v| v["created_at"] <=> k["created_at"]} + entries = entries.sort{|k,v| v["created_at"] <=> k["created_at"]} if !params["sort"].present? entries = Kaminari.paginate_array(entries).page(params["page_no"]).per(OrbitHelper.page_data_count) else - entries = table.table_entries.desc(:created_at).page(params["page_no"]).per(OrbitHelper.page_data_count) + if params["sort"].present? + reset = "" + column_to_sort = table.table_columns.where(:key => params["sortcolumn"]).first + case column_to_sort.type + when "text" + field_name = :text + when "editor" + field_name = :content + when "date" + field_name = :date + end + columns = column_to_sort.column_entries.order_by(field_name => params["sort"]) + entries = [] + columns.each do |column| + entries << column.table_entry + end + entries = Kaminari.paginate_array(entries).page(params["page_no"]).per(OrbitHelper.page_data_count) + else + entries = table.table_entries.desc(:created_at).page(params["page_no"]).per(OrbitHelper.page_data_count) + end end + total_pages = entries.total_pages entries.each do |te| cols = [] + sort_value = "" tablecolumns.each do |column| ce = te.column_entries.where(:table_column_id => column.id).first rescue nil if !ce.nil? @@ -56,19 +135,20 @@ class UniversalTablesController < ApplicationController when "editor" text = ce.content when "date" - text = ce.date.strftime("%Y-%m-%d %H:%M") + text = format_date(ce.date, column.date_format) when "period" - text = (ce.period_from.strftime("%Y-%m-%d") rescue "") + " ~ " + (ce.period_to.strftime("%Y-%m-%d") rescue "") - text = "" if text.starts_with?("~") + text = format_date(ce.period_from, column.date_format) + " ~ " + format_date(ce.period_to, column.date_format) + text = "" if text.starts_with?(" ~") when "image" text = "" end if column.is_link_to_show text = "#{text}" end - cols << { - "text" => text - } + + cols << {"text" => text} + else + cols << {"text" => ""} end end rows << { @@ -79,9 +159,10 @@ class UniversalTablesController < ApplicationController { "head-columns" => table_heads, "rows" => rows, - "total_pages" => entries.total_pages, + "total_pages" => total_pages, "extras" => { "table-name" => table.title, + "reset" => reset, "url" => "/#{I18n.locale.to_s}#{page.url}" } } @@ -101,18 +182,19 @@ class UniversalTablesController < ApplicationController when "editor" text = ce.content when "date" - text = ce.date.strftime("%Y-%m-%d %H:%M") + text = format_date(ce.date, ce.table_column.date_format) when "period" - text = (ce.period_from.strftime("%Y-%m-%d") rescue "") + " ~ " + (ce.period_to.strftime("%Y-%m-%d") rescue "") - text = "" if text.starts_with?("~") + text = format_date(ce.period_from, ce.table_column.date_format) + " ~ " + format_date(ce.period_from, ce.table_column.date_format) + text = "" if text.starts_with?(" ~") when "image" text = "" end + rows << { "title" => ct.title, "text" => text, "order" => ct.order - } + } if text != "" end sorted = rows.sort{ |k,v| k["order"] <=> v["order"] } { diff --git a/app/helpers/admin/universal_tables_helper.rb b/app/helpers/admin/universal_tables_helper.rb new file mode 100644 index 0000000..2a53e9d --- /dev/null +++ b/app/helpers/admin/universal_tables_helper.rb @@ -0,0 +1,31 @@ +module Admin::UniversalTablesHelper + + def format_date(date, format, for_editing=false) + case format + when "yyyy/MM/dd hh:mm" + f = "%Y/%m/%d %H:%M" + when "yyyy/MM/dd" + f = "%Y/%m/%d" + when "yyyy/MM" + f = "%Y/%m" + when "yyyy" + f = "%Y" + f = "%Y/%m" if for_editing + end + d = date.strftime(f) rescue "" + return d + end + + def render_unique_texts(f,column,i) + select_values = column.column_entries.distinct(:text).uniq + select = "" + "
Or " + select + "
" + end + +end diff --git a/app/helpers/universal_table/application_helper.rb b/app/helpers/universal_table/application_helper.rb deleted file mode 100644 index 6f58001..0000000 --- a/app/helpers/universal_table/application_helper.rb +++ /dev/null @@ -1,4 +0,0 @@ -module UniversalTable - module ApplicationHelper - end -end diff --git a/app/models/table_column.rb b/app/models/table_column.rb index ede9193..7127424 100644 --- a/app/models/table_column.rb +++ b/app/models/table_column.rb @@ -6,8 +6,10 @@ class TableColumn field :title, localize: true field :display_in_index, type: Boolean, default: true field :type + field :date_format, default: "YYYY/MM//DD" field :is_link_to_show, type: Boolean, default: false field :order, type: Integer + field :make_categorizable, type: Boolean, default: false belongs_to :u_table diff --git a/app/models/u_table.rb b/app/models/u_table.rb index 7040c7d..51e10fc 100644 --- a/app/models/u_table.rb +++ b/app/models/u_table.rb @@ -12,4 +12,5 @@ class UTable accepts_nested_attributes_for :table_columns, :allow_destroy => true FIELD_TYPES = ["text", "editor", "image", "date", "period"] + DATE_FORMATS = ["yyyy/MM/dd hh:mm", "yyyy/MM/dd","yyyy/MM", "yyyy"] end \ No newline at end of file diff --git a/app/views/admin/universal_tables/_column.html.erb b/app/views/admin/universal_tables/_column.html.erb index 6f84f4d..e6b90f3 100644 --- a/app/views/admin/universal_tables/_column.html.erb +++ b/app/views/admin/universal_tables/_column.html.erb @@ -2,12 +2,12 @@
<% end %>
- Delete + Delete <% if defined?(i) %> <%= f.hidden_field :_destroy, :value => "false", :class => "attribute_field_to_delete" %> -

<%= column.title %>

+

<%= column.title %>

<% else %> -

ColumnXX

+

ColumnXX

<% end %>
@@ -59,21 +59,30 @@
<% select_values = UTable::FIELD_TYPES.collect{|ft| [ft.capitalize,ft]} %> <%= f.select :type, select_values, {}, {class: "type-selector"} %> -
<% if defined?(i) %> <% if column.order.nil? %> - <%= f.hidden_field :order, :value => i %> + <%= f.hidden_field :order, :value => i, :class => "order-hidden-field" %> <% else %> - <%= f.hidden_field :order %> + <%= f.hidden_field :order, :class => "order-hidden-field" %> <% end %> <% else %> - <%= f.hidden_field :order, :value=> "XXX" %> + <%= f.hidden_field :order, :value=> "XXX", :class => "order-hidden-field" %> <% end %>
<% if !defined?(i) %> -
+
<% end %> \ No newline at end of file diff --git a/app/views/admin/universal_tables/_date_field.html.erb b/app/views/admin/universal_tables/_date_field.html.erb index 3de0a9b..28cd4ec 100644 --- a/app/views/admin/universal_tables/_date_field.html.erb +++ b/app/views/admin/universal_tables/_date_field.html.erb @@ -3,7 +3,8 @@
- <%= f.text_field :date, :value => (date_field.date.strftime("%Y/%m/%d %H:%M") rescue ""), :placeholder => "YYYY/MM/DD HH:MM", :data => {:format => "yyyy/MM/dd hh:mm"} %> + <% v = !date_field.new_record? ? format_date(date_field.date, column.date_format, true) : "" %> + <%= f.text_field :date, :value => v, :placeholder => column.date_format.upcase, :data => {:format => (column.date_format == "yyyy" ? "yyyy/MM" : column.date_format)} %>
diff --git a/app/views/admin/universal_tables/_period_field.html.erb b/app/views/admin/universal_tables/_period_field.html.erb index f0d7e0c..0febe1f 100644 --- a/app/views/admin/universal_tables/_period_field.html.erb +++ b/app/views/admin/universal_tables/_period_field.html.erb @@ -4,7 +4,8 @@
- <%= f.text_field :period_from, :value => (period_field.period_from.strftime("%Y/%m/%d") rescue ""), :placeholder => "YYYY/MM/DD", :data => {:format => "yyyy/MM/dd"}, :class => "input-small" %> + <% v = !period_field.new_record? ? format_date(period_field.period_from, column.date_format, true) : "" %> + <%= f.text_field :period_from, :value => v, :placeholder => column.date_format.upcase, :data => {:format => (column.date_format == "yyyy" ? "yyyy/MM" : column.date_format)}, :class => "input-small" %>
@@ -16,7 +17,8 @@
- <%= f.text_field :period_to,:value => (period_field.period_to.strftime("%Y/%m/%d") rescue ""), :placeholder => "YYYY/MM/DD", :data => {:format => "yyyy/MM/dd"}, :class => "input-small" %> + <% v = !period_field.new_record? ? format_date(period_field.period_to, column.date_format, true) : "" %> + <%= f.text_field :period_to,:value => v, :placeholder => column.date_format.upcase, :data => {:format => (column.date_format == "yyyy" ? "yyyy/MM" : column.date_format)}, :class => "input-small" %>
diff --git a/app/views/admin/universal_tables/_table_form.html.erb b/app/views/admin/universal_tables/_table_form.html.erb index 20bf963..f556548 100644 --- a/app/views/admin/universal_tables/_table_form.html.erb +++ b/app/views/admin/universal_tables/_table_form.html.erb @@ -1,6 +1,9 @@ <% content_for :page_specific_css do %> <%= stylesheet_link_tag "universal_table/universal-table" %> <% end %> + <% content_for :page_specific_javascript do %> + <%= javascript_include_tag "universal_table/jquery-ui.min" %> +<% end %>
@@ -68,10 +71,13 @@ if($(this).parent().find(".attribute_field_to_delete").length == 0){ $(this).parent().parent().slideUp(function(){ $(this).remove(); + updateOrder(); }); }else{ if(confirm("Are you sure?")){ - $(this).parent().parent().slideUp(); + $(this).parent().parent().slideUp(function(){ + updateOrder(); + }); $(this).parent().find(".attribute_field_to_delete").val("true"); } } @@ -80,15 +86,35 @@ $(document.body).on("change","select.type-selector",function(){ var el = $(this), - label = el.parent().find("label"); + label = el.parent().find("span.link_to_show"); if(el.val() == "text"){ label.removeClass("hide"); }else{ label.addClass("hide"); label.find("input[type=checkbox]").prop("checked",false); } + label = el.parent().find("label.date_format"); + if(el.val() == "date" || el.val() == "period"){ + label.removeClass("hide"); + }else{ + label.addClass("hide"); + } }) + $("#attributes-area").sortable({ + update: function( event, ui ) { + updateOrder(); + } + }); + + var updateOrder = function(){ + var attributes = $("#attributes-area").find(".attributes:visible"); + attributes.each(function(i){ + $(this).find("input.order-hidden-field").val(i); + }) + } + + diff --git a/app/views/admin/universal_tables/_text_field.html.erb b/app/views/admin/universal_tables/_text_field.html.erb index 991924f..f2fbdf6 100644 --- a/app/views/admin/universal_tables/_text_field.html.erb +++ b/app/views/admin/universal_tables/_text_field.html.erb @@ -8,7 +8,7 @@ <% id = "table_entry_column_entries_#{i}_text_translations_#{locale.to_s}" %>
<%= f.fields_for :text_translations do |f| %> - <%= f.text_field locale, :value => text_field.text_translations[locale.to_s] %> + <%= f.text_field locale, :value => text_field.text_translations[locale.to_s], :for => locale.to_s %> <% end %>
<% end %> @@ -21,6 +21,22 @@ <% end %>
+ <% if column.make_categorizable %> + <%= render_unique_texts(f,column,i).html_safe %> + + <% end %> +
<% if !text_field.new_record? %> <%= f.hidden_field :id %> diff --git a/app/views/admin/universal_tables/show.html.erb b/app/views/admin/universal_tables/show.html.erb index 652d051..e05d5da 100644 --- a/app/views/admin/universal_tables/show.html.erb +++ b/app/views/admin/universal_tables/show.html.erb @@ -1,11 +1,14 @@ <% content_for :page_specific_css do %> <%= stylesheet_link_tag "universal_table/universal-table" %> <% end %> - - +
@@ -34,10 +37,10 @@ <% end %> <% when "date" %> - <%= ce.date.strftime("%Y-%m-%d %H:%M") rescue "" %> + <%= format_date(ce.date, column.date_format) %> <% when "period" %> <% if !ce.period_from.nil? %> - <%= ce.period_from.strftime("%Y-%m-%d") rescue "" %> ~ <%= ce.period_to.strftime("%Y-%m-%d") rescue "" %> + <%= format_date(ce.period_from, column.date_format) %> ~ <%= format_date(ce.period_to, column.date_format) %> <% end %> <% end %> <% if index == 0 %> @@ -49,6 +52,10 @@ <% end %> + <% else %> + <% end %> <% end %> @@ -65,8 +72,6 @@ - - diff --git a/config/locales/zh_tw.yml b/config/locales/zh_tw.yml index 730d015..4dff978 100644 --- a/config/locales/zh_tw.yml +++ b/config/locales/zh_tw.yml @@ -1,6 +1,6 @@ zh_tw: universal_table: - universal_table: Universal Table + universal_table: 萬用表格 all_tables: All Tables new_table: Create New Table table_name: Table Name
+   +