From e3d2fd9a1758c3aa9c8bdab5811f31fe2f9e31d3 Mon Sep 17 00:00:00 2001 From: Rob Garrison Date: Sun, 25 Oct 2015 20:10:43 -0500 Subject: [PATCH] Group: Improve compatibility with jQuery Globalize Added `group_time24Hour` & `group_dateInvalid` options Modified `group_months`, `group_week` and `group_time` options. --- dist/js/widgets/widget-grouping.min.js | 4 +- docs/example-widget-grouping.html | 291 +++++++++++++++++++++++-- docs/index.html | 2 +- js/widgets/widget-grouping.js | 63 +++++- 4 files changed, 330 insertions(+), 30 deletions(-) diff --git a/dist/js/widgets/widget-grouping.min.js b/dist/js/widgets/widget-grouping.min.js index 1916cf86..cc05fe76 100644 --- a/dist/js/widgets/widget-grouping.min.js +++ b/dist/js/widgets/widget-grouping.min.js @@ -1,2 +1,2 @@ -/*! Widget: grouping - updated 9/1/2015 (v2.23.3) */ -!function(a){"use strict";var b=a.tablesorter;b.grouping={types:{number:function(a,c,d,e,f){var g,h;return e>1&&""!==d?c.hasClass(b.css.sortAsc)?(g=Math.floor(parseFloat(d)/e)*e,g>parseFloat(f||0)?g:parseFloat(f||0)):(g=Math.ceil(parseFloat(d)/e)*e,g=e?h[e-1]:d||"")},separator:function(b,c,d,e){var f=(d+"").split(b.widgetOptions.group_separator);return a.trim(f&&e>0&&f.length>=e?f[(e||1)-1]:"")},word:function(a,b,c,d){var e=(c+" ").match(/\w+/g);return e&&e.length>=d?e[d-1]:c||""},letter:function(a,b,c,d){return c?(c+" ").substring(0,d):""},date:function(a,b,c,d,e){var f=a.widgetOptions,g=new Date(c||""),h=g.getHours();return"year"===d?g.getFullYear():"month"===d?f.group_months[g.getMonth()]:"monthyear"===d?f.group_months[g.getMonth()]+" "+g.getFullYear():"day"===d?f.group_months[g.getMonth()]+" "+g.getDate():"week"===d?f.group_week[g.getDay()]:"time"===d?("00"+(h>12?h-12:0===h?h+12:h)).slice(-2)+":"+("00"+g.getMinutes()).slice(-2)+" "+("00"+f.group_time[h>=12?1:0]).slice(-2):f.group_dateString(g)}},update:function(c,d,e){if(!a.isEmptyObject(d.cache)){var f,g,h,i,j,k,l,m,n,o="undefined"!=typeof d.sortList[0],p="",q=0,r=!1,s=a.isArray(e.group_forceColumn)&&"undefined"!=typeof e.group_forceColumn[0]?e.group_enforceSort&&!o?-1:e.group_forceColumn[0]:o?d.sortList[0][0]:-1;if(d.$table.find("tr.group-hidden").removeClass("group-hidden").end().find("tr.group-header").remove(),e.group_collapsible&&d.$table.data("pagerSavedHeight",0),s>=0&&s1&&""!==h&&(h+=" - "+(parseInt(h,10)+(parseInt(k[2],10)-1)*(d.$headerIndexed[s].hasClass(b.css.sortAsc)?1:-1))),a.isFunction(e.group_formatter)&&(h=e.group_formatter((h||"").toString(),s,c,d,e)||h),i.eq(f).before(''+(e.group_collapsible?"":"")+''+h+''),e.group_saveGroups&&!r&&e.group_collapsed&&e.group_collapsible&&e.group_currentGroups[e.group_currentGroup].push(h)));d.$table.find("tr.group-header").bind("selectstart",!1).each(function(){var b,d,f,g=a(this),h=g.nextUntil("tr.group-header").filter(":visible");(e.group_count||a.isFunction(e.group_callback))&&(d=g.find(".group-count"),d.length&&(e.group_count&&d.html(e.group_count.replace(/\{num\}/g,h.length)),a.isFunction(e.group_callback)&&e.group_callback(g.find("td"),h,s,c))),e.group_saveGroups&&!a.isEmptyObject(e.group_currentGroups)&&e.group_currentGroups[e.group_currentGroup].length?(f=g.find(".group-name").text().toLowerCase()+g.attr("data-group-index"),b=a.inArray(f,e.group_currentGroups[e.group_currentGroup])>-1,g.toggleClass("collapsed",b),h.toggleClass("group-hidden",b)):e.group_collapsed&&e.group_collapsible&&(g.addClass("collapsed"),h.addClass("group-hidden"))}),d.$table.trigger(e.group_complete)}}},bindEvents:function(c,d,e){e.group_collapsible&&(e.group_currentGroups=[],d.$table.on("click toggleGroup keyup","tr.group-header",function(f){if(f.stopPropagation(),"keyup"!==f.type||13===f.which){var g,h,i,j=a(this),k=j.find(".group-name").text().toLowerCase()+j.attr("data-group-index");!f.shiftKey||"click"!==f.type&&"keyup"!==f.type||j.siblings(".group-header").trigger("toggleGroup"),j.toggleClass("collapsed"),j.nextUntil("tr.group-header").toggleClass("group-hidden",j.hasClass("collapsed")),e.group_saveGroups&&b.storage&&(h=d.$table.find(".group-header"),g=j.hasClass("collapsed"),e.group_currentGroups[e.group_currentGroup]||(e.group_currentGroups[e.group_currentGroup]=[]),g&&e.group_currentGroup?e.group_currentGroups[e.group_currentGroup].push(k):e.group_currentGroup&&(i=a.inArray(k,e.group_currentGroups[e.group_currentGroup]),i>-1&&e.group_currentGroups[e.group_currentGroup].splice(i,1)),b.storage(c,"tablesorter-groups",e.group_currentGroups))}})),a(e.group_saveReset).on("click",function(){b.grouping.clearSavedGroups(c)}),d.$table.on("pagerChange.tsgrouping",function(){b.grouping.update(c,d,e)})},clearSavedGroups:function(a){a&&b.storage&&(b.storage(a,"tablesorter-groups",""),b.grouping.update(a,a.config,a.config.widgetOptions))}},b.addWidget({id:"group",priority:100,options:{group_collapsible:!0,group_collapsed:!1,group_saveGroups:!0,group_saveReset:null,group_count:" ({num})",group_separator:"-",group_formatter:null,group_callback:null,group_complete:"groupingComplete",group_forceColumn:[],group_enforceSort:!0,group_checkbox:["checked","unchecked"],group_months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],group_week:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],group_time:["AM","PM"],group_dateString:function(a){return a.toLocaleString()}},init:function(a,c,d,e){b.grouping.bindEvents(a,d,e)},format:function(a,c,d){b.grouping.update(a,c,d)},remove:function(a,b,c){b.$table.off("click","tr.group-header").off("pagerChange.tsgrouping").find(".group-hidden").removeClass("group-hidden").end().find("tr.group-header").remove()}})}(jQuery); \ No newline at end of file +/*! Widget: grouping - updated 10/25/2015 (v2.23.6) */ +!function(a){"use strict";var b=a.tablesorter;b.grouping={types:{number:function(a,c,d,e,f){var g,h;return e>1&&""!==d?c.hasClass(b.css.sortAsc)?(g=Math.floor(parseFloat(d)/e)*e,g>parseFloat(f||0)?g:parseFloat(f||0)):(g=Math.ceil(parseFloat(d)/e)*e,g=e?h[e-1]:d||"")},separator:function(b,c,d,e){var f=(d+"").split(b.widgetOptions.group_separator);return a.trim(f&&e>0&&f.length>=e?f[(e||1)-1]:"")},word:function(a,b,c,d){var e=(c+" ").match(/\w+/g);return e&&e.length>=d?e[d-1]:c||""},letter:function(a,b,c,d){return c?(c+" ").substring(0,d):""},date:function(a,c,d,e,f){var g,h,i=a.widgetOptions,j=new Date(d||"");return j instanceof Date&&isFinite(j)?(g=j.getFullYear(),h=b.grouping.findMonth(i,j.getMonth()),"year"===e?g:"month"===e?h:"monthyear"===e?h+" "+g:"day"===e?h+" "+j.getDate():"week"===e?b.grouping.findWeek(i,j.getDay()):"time"===e?b.grouping.findTime(i,j):i.group_dateString(j,a,c)):i.group_dateInvalid}},findMonth:function(a,b){return a.group_months[b+(""===(a.group_months[0]||"")?1:0)]},findWeek:function(b,c){if(a.isArray(b.group_week))return b.group_week[c];if(!a.isEmptyObject(b.group_week)){var d=["sun","mon","tue","wed","thu","fri","sat"];return b.group_week[d[c]]}},findTime:function(a,b){var c,d=b.getHours(),e=d>=12?1:0,f=a.group_time.am&&a.group_time.pm,g=("00"+(a.group_time24Hour&&d>12?d-12:a.group_time24Hour&&0===d?d+12:d)).slice(-2),h=("00"+b.getMinutes()).slice(-2);return c=a.group_time[f?["am","pm"][e]:e],g+":"+h+(a.group_time24Hour?"":" "+(c||""))},update:function(c,d,e){if(!a.isEmptyObject(d.cache)){var f,g,h,i,j,k,l,m,n,o="undefined"!=typeof d.sortList[0],p="",q=0,r=!1,s=a.isArray(e.group_forceColumn)&&"undefined"!=typeof e.group_forceColumn[0]?e.group_enforceSort&&!o?-1:e.group_forceColumn[0]:o?d.sortList[0][0]:-1;if(d.$table.find("tr.group-hidden").removeClass("group-hidden").end().find("tr.group-header").remove(),e.group_collapsible&&d.$table.data("pagerSavedHeight",0),s>=0&&s1&&""!==h&&(h+=" - "+(parseInt(h,10)+(parseInt(k[2],10)-1)*(d.$headerIndexed[s].hasClass(b.css.sortAsc)?1:-1))),a.isFunction(e.group_formatter)&&(h=e.group_formatter((h||"").toString(),s,c,d,e)||h),i.eq(f).before(''+(e.group_collapsible?"":"")+''+h+''),e.group_saveGroups&&!r&&e.group_collapsed&&e.group_collapsible&&e.group_currentGroups[e.group_currentGroup].push(h)));d.$table.find("tr.group-header").bind("selectstart",!1).each(function(){var b,d,f,g=a(this),h=g.nextUntil("tr.group-header").filter(":visible");(e.group_count||a.isFunction(e.group_callback))&&(d=g.find(".group-count"),d.length&&(e.group_count&&d.html(e.group_count.replace(/\{num\}/g,h.length)),a.isFunction(e.group_callback)&&e.group_callback(g.find("td"),h,s,c))),e.group_saveGroups&&!a.isEmptyObject(e.group_currentGroups)&&e.group_currentGroups[e.group_currentGroup].length?(f=g.find(".group-name").text().toLowerCase()+g.attr("data-group-index"),b=a.inArray(f,e.group_currentGroups[e.group_currentGroup])>-1,g.toggleClass("collapsed",b),h.toggleClass("group-hidden",b)):e.group_collapsed&&e.group_collapsible&&(g.addClass("collapsed"),h.addClass("group-hidden"))}),d.$table.trigger(e.group_complete)}}},bindEvents:function(c,d,e){e.group_collapsible&&(e.group_currentGroups=[],d.$table.on("click toggleGroup keyup","tr.group-header",function(f){if(f.stopPropagation(),"keyup"!==f.type||13===f.which){var g,h,i,j=a(this),k=j.find(".group-name").text().toLowerCase()+j.attr("data-group-index");!f.shiftKey||"click"!==f.type&&"keyup"!==f.type||j.siblings(".group-header").trigger("toggleGroup"),j.toggleClass("collapsed"),j.nextUntil("tr.group-header").toggleClass("group-hidden",j.hasClass("collapsed")),e.group_saveGroups&&b.storage&&(h=d.$table.find(".group-header"),g=j.hasClass("collapsed"),e.group_currentGroups[e.group_currentGroup]||(e.group_currentGroups[e.group_currentGroup]=[]),g&&e.group_currentGroup?e.group_currentGroups[e.group_currentGroup].push(k):e.group_currentGroup&&(i=a.inArray(k,e.group_currentGroups[e.group_currentGroup]),i>-1&&e.group_currentGroups[e.group_currentGroup].splice(i,1)),b.storage(c,"tablesorter-groups",e.group_currentGroups))}})),a(e.group_saveReset).on("click",function(){b.grouping.clearSavedGroups(c)}),d.$table.on("pagerChange.tsgrouping",function(){b.grouping.update(c,d,e)})},clearSavedGroups:function(a){a&&b.storage&&(b.storage(a,"tablesorter-groups",""),b.grouping.update(a,a.config,a.config.widgetOptions))}},b.addWidget({id:"group",priority:100,options:{group_collapsible:!0,group_collapsed:!1,group_saveGroups:!0,group_saveReset:null,group_count:" ({num})",group_separator:"-",group_formatter:null,group_callback:null,group_complete:"groupingComplete",group_forceColumn:[],group_enforceSort:!0,group_checkbox:["checked","unchecked"],group_months:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],group_week:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],group_time:["AM","PM"],group_time24Hour:!1,group_dateInvalid:"Invalid Date",group_dateString:function(a){return a.toLocaleString()}},init:function(a,c,d,e){b.grouping.bindEvents(a,d,e)},format:function(a,c,d){b.grouping.update(a,c,d)},remove:function(a,b,c){b.$table.off("click","tr.group-header").off("pagerChange.tsgrouping").find(".group-hidden").removeClass("group-hidden").end().find("tr.group-header").remove()}})}(jQuery); \ No newline at end of file diff --git a/docs/example-widget-grouping.html b/docs/example-widget-grouping.html index 2fb1cff0..4a96c8fb 100644 --- a/docs/example-widget-grouping.html +++ b/docs/example-widget-grouping.html @@ -98,6 +98,11 @@ tr.group-header.collapsed td i { group_week : [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], group_time : [ "AM", "PM" ], + // use 12 vs 24 hour time + group_time24Hour : false, + // group header text added for invalid dates + group_dateInvalid : 'Invalid Date', + // this function is used when "group-date" is set to create the date string // you can just return date, date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString() // reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Conversion_getter @@ -155,6 +160,17 @@ tr.group-header.collapsed td i {
  • This widget will only work in tablesorter version 2.8+ and jQuery version 1.7+.
  • Please do not use this widget in very large tables (it might be really slow) or when your table includes multiple tbodies.

  • +
  • In v2.23.6 +
      +
    • Added group_time24Hour (set 12 vs 24 hour time) & group_dateInvalid (group header text) options.
    • +
    • Improved compatibility of the group widget with jQuery Globalize.
    • +
    • The group_months option will now accept a zero or one-based array or object of month names.
    • +
    • The group_week option will now accept an object using three-letter English weekday abbreviations as a key.
    • +
    • The group_time option will now accept an object using "am" or "pm" as a key.
    • +
    • For more detail, see the description column for the option in the Options section below.
    • +
    • For information on how to load & use Globalize, see the Globalization section below.
    • +
    +
  • In v2.23.3
    • Added group_forceColumn & group_enforceSort options for force column grouping.
    • @@ -313,7 +329,7 @@ group_separator : /[/.]/ - [] + [] Force the group widget to only apply to one column (v2.23.3).
      @@ -347,32 +363,105 @@ group_separator : /[/.]/ - -
      - group_week
      - group_time - + (see description) - Name arrays included so that the language of the date groups can be modified easily. Defaults (English): -
        -
      • group_months: ([ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]) - Month names.
      • -
      • group_week: ([ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]) - Named days of the week.
      • -
      • group_time: ([ "AM", "PM" ]) - Time of day.
      • -
      + Name arrays included so that the language of the date groups can be modified easily (v2.23.6; see "Globalization" section for details). +
      +

      Showing defaults (English):

      +
      // zero-based array
      +group_months: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
      + As of v2.23.6, this option will also work with an object with a one-base "index": +
      // get Months list from CLDR (see Globalization section for more info)
      +var months = new Cldr( 'en' ).main([ "dates/calendars/gregorian/months", "format", "abbreviated" ]);
      +// one-based object (CLDR output example)
      +// months = { 1: "Jan", 2: "Feb", 3: "Mar", 4: "Apr", 5: "May", 6: "Jun", 7: "Jul", 8: "Aug", 9: "Sep", 10: "Oct", 11: "Nov", 12: "Dec" }
      +// then in the widgetOptions,
      +group_months: months
      + A one-based array of month names will also work. +
      group_months: [ "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
      +
      + + + + (see description) + + Name arrays included so that the language of the date groups can be modified easily (v2.23.6; see "Globalization" for details). +
      +

      Showing defaults (English):

      +
      // zero-based index
      +group_week: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ]
      + As of v2.23.6, this option will also work with an object using a three-letter English weekday abbreviated names as a key: +
      // get weekdays list from CLDR (see Globalization section for more info)
      +var weekdays = new Cldr( 'en' ).main([ "dates/calendars/gregorian/days", "format", "abbreviated" ]);
      +// week-abbreviation based object
      +// weekdays = { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat" }
      +// then in the widgetOptions,
      +group_week: weekdays
      + At this point, if you're going to use Globalization, it would be best to use the group_dateString to use globalize.dateFormatter to format the date because not all locales start their week on Sunday. +
      + + + + + + (see description) + + Name arrays included so that the language of the date groups can be modified easily (v2.23.6; see "Globalization" for details). +
      +

      Defaults (English):

      +
      group_time: [ "AM", "PM" ]
      + As of v2.23.6, this option will also work with an object in this format: +
      // get time of day list from CLDR (see Globalization section for more info)
      +var periods = cldr.main([ "dates/calendars/gregorian/dayPeriods", "format", "abbreviated" ]);
      +/* time of day: CLDR returns this object:
      +peroids = {
      +	afternoon1: "in the afternoon",
      +	am: "AM",
      +	am-alt-variant: "am",
      +	evening1: "in the evening",
      +	midnight: "midnight",
      +	morning1: "in the morning",
      +	night1: "at night",
      +	noon: "noon",
      +	pm: "PM",
      +	pm-alt-variant: "pm"
      +}
      +then in the widgetOptions,*/
      +group_time: periods
      + If you want to use a time of day other than "am" or "pm", then you'll need to use the group_dateString to format the date; see the example in the Globalization section below. +
      + + + + + group_time24Hour + false + Set to true to display time in 24 hour format (v2.23.6). + + + + group_dateInvalid + 'Invalid Date' + Message added to the Group header if a date is invalid (v2.23.6). + + (see description) - When the "group-date" class name is set on a column, this function is used to format the date string. This is the default function: + When the "group-date" class name is set on a column, this function is used to format the date string (v2.23.6).
      -
      // you can just return date, date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString()
      -group_dateString : function(date) {
      +							

      This is the default function:

      +
      // you can just return date, date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString()
      +group_dateString : function(date, config, $header ) {
         return date.toLocaleString();
       }
      Other functions that can be used are date (alone), date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString(). See this reference for more details. +

      In v2.23.6, this widget was updated to make it easier to use with jQuery Globalize.

      +

      Additionally, two new parameters were added: config and $header (a jQuery object of the associated header cell).

      @@ -466,6 +555,178 @@ group_dateString : function(date) { * When sorting some columns, different group headers with the same group name may exist (try "group-date-week" and "group-date-time"). To make these columns sort specifically by the group you want, you'll need to modify the parser.
      + +

      Globalization

      +
      +

      jQuery Globalize

      + These instructions are specific to jQuery Globalize. +

      Here is a demo showing how all the code comes together; there is no official site with JSON files available to load into the demo, so only the required snippets of CLDR data are included in the demo.

      +

      Make sure to include files from:

      +
        +
      • jQuery Globalize: +
          +
        • Process CLDR data into usable formats.
        • +
        • Install from npm (npm install globalize cldr-data), bower (bower install globalize), or
        • +
        • Download from https://github.com/jquery/globalize.
        • +
        • Depending on the data in your table, you'll need to pick which modules to include; currently for the date module, you'll need to load the number module first (ref).
        • +
        • Here is an example of how to load all files from Cdnjs (make sure to use the most recent version): +
          <script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/currency.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/number.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/date.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/message.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/plural.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/globalize/1.0.0/globalize/relative-time.min.js"></script>
          +
          +
        • +
        +
      • +
      • cldrjs: +
          +
        • Needed by Globalize to traverse CLDR data.
        • +
        • Install from npm (npm install cldrjs), bower (bower install cldrjs), or
        • +
        • Download from https://github.com/rxaviers/cldrjs.
        • +
        • You will likely need to include all files: cldr.js, event.js, supplemental.js and unresolved.js.
        • +
        • Here is an example of how to load all files from Cdnjs (make sure to use the most recent version): +
          <script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr/event.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr/supplemental.min.js"></script>
          +<script src="https://cdnjs.cloudflare.com/ajax/libs/cldrjs/0.4.3/cldr/unresolved.min.js"></script>
          +
          +
        • +
        +
      • +
      • CLDR data: + +
      • +
      + +

      Initialization

      + The next step is loading the CLDR data into Globalize; please see this page for more details. + +
      +// code to show how to load a language using jQuery (make sure it was loaded)
      +$(function() {
      +	var hasInitialized = false,
      +		loadLanguage = function( lang ) {
      +			// Use $.getJSON instead of $.get if your server is not configured to return the
      +			// right MIME type for .json files.
      +			var files = [];
      +			if ( !hasInitialized ) {
      +				files = [
      +					/* core */
      +					$.getJSON( 'cldr-data/supplemental/likelySubtags.json' ),
      +					/* currency */
      +					$.getJSON( 'cldr-data/supplemental/currencyData.json' ),
      +					/* date */
      +					$.getJSON( 'cldr-data/supplemental/timeData.json' ),
      +					$.getJSON( 'cldr-data/supplemental/weekData.json' ),
      +					/* number */
      +					$.getJSON( 'cldr-data/supplemental/numberingSystems.json' ),
      +					/* plural */
      +					$.getJSON( 'cldr-data/supplemental/plurals.json' ),
      +					$.getJSON( 'cldr-data/supplemental/ordinals.json' )
      +				];
      +			}
      +			files = files.concat([
      +				/* currency */
      +				$.getJSON( 'cldr-data/main/' + lang + '/currencies.json' ),
      +				/* date */
      +				$.getJSON( 'cldr-data/main/' + lang + '/ca-gregorian.json' ),
      +				$.getJSON( 'cldr-data/main/' + lang + '/timeZoneNames.json' ),
      +				/* number */
      +				$.getJSON( 'cldr-data/main/' + lang + '/numbers.json' ),
      +				/* relative time */
      +				$.getJSON( 'cldr-data/main/' + lang + '/dateFields.json' ),
      +				/* unit */
      +				$.getJSON( 'cldr-data/main/' + lang + '/units.json' )
      +			]);
      +			$.when
      +				.apply( $, files )
      +				.then( function() {
      +					// Normalize $.get results, we only need the JSON, not the request statuses.
      +					return [].slice.apply( arguments, [ 0 ] ).map( function( result ) {
      +						return result[ 0 ];
      +					});
      +				})
      +				.then( Globalize.load )
      +				.then( function() {
      +					if ( !hasInitialized ) {
      +						// initialization code goes here
      +					}
      +					hasInitialized = true;
      +					// code to run after each new language has loaded goes here
      +				});
      +		};
      +
      +	// initial language load
      +	loadLanguage( 'en' );
      +});
      +
      + +

      Usage

      + Use Globalize with tablesorter & the group widget inside of the group_dateString callback function. +

      In v2.23.6

      +
        +
      • The group_months, group_week & group_time options were modified to work with CLDR data.
      • +
      • group_months option will work with either a zero-based array of month names (basic use), or an object with a key using a one-based indexed with a month name value pair (the CLDR format; see the "months" comment in code example below).
      • +
      • group_week option will work with either a zero-based array of weekday names (basic use), or an object with a key using three letter abbreviations of English weekday names with a localized weekday name value pair (the CLDR format; see the "days of week" comment in the code below).
      • +
      • group_time option will now accept an object using "am" or "pm" (both lower case) as a key.

      • + +
      • The group_dateString callback function was updated with two additional parameters to allow access to table data. See the "Options" section above for more details.
      • +
      • Check out this demo using the code below
      • +
      +
      $( function() {
      +	// using an english example
      +	var lang = 'en',
      +		cldr = new Cldr( lang ),
      +		// Globalize.load already done!!
      +		globalize = Globalize.locale( lang ),
      +		// months: CLDR returns an object { 1: "Jan", 2: "Feb", 3: "Mar", ..., 12: "Dec" }
      +		months = cldr.main([ "dates/calendars/gregorian/months", "format", "abbreviated" ]),
      +		// days of week: CLDR returns { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", ... }
      +		week = cldr.main([ "dates/calendars/gregorian/days", "format", "abbreviated" ]),
      +		/* time of day: CLDR returns
      +			{ afternoon1: "in the afternoon", am: "AM", am-alt-variant: "am", evening1: "in the evening", midnight: "midnight",
      +			  morning1: "in the morning", night1: "at night", noon: "noon", pm: "PM", pm-alt-variant: "pm" } */
      +		periods = cldr.main([ "dates/calendars/gregorian/dayPeriods", "format", "abbreviated" ]);
      +
      +	$( 'table' ).tablesorter({
      +		theme : 'blue',
      +		widgets: [ 'group', 'zebra' ],
      +		widgetOptions : {
      +			group_months     : months,
      +			group_week       : week,
      +			// setting group_times to an empty string forces "group-time" to use group_dateString function
      +			group_time       : periods,
      +			group_dateString : function ( date, c, $column ) {
      +				// see https://github.com/jquery/globalize/blob/master/doc/api/date/date-formatter.md
      +				var hour = date.getHours(),
      +					min = date.getMinutes(),
      +					format = globalize.dateFormatter({ datetime: "full" })( date ),
      +					time = globalize.dateFormatter({ time: "full" })( date );
      +				// replace special times with time period
      +				if ( hour === 0 && min === 0 ) {
      +					// midnight: this method may not work in all locales!
      +					return format.replace( time, periods.midnight );
      +				} else if ( hour === 12 && min === 0 ) {
      +					// noon: this method may not work in all locales!
      +					return format.replace( time, periods.noon );
      +				}
      +				return format;
      +			}
      +		}
      +	});
      +
      +});
      +
      +

      diff --git a/docs/index.html b/docs/index.html index b2f145f2..4cb913f7 100644 --- a/docs/index.html +++ b/docs/index.html @@ -473,7 +473,7 @@
    • Beta Formatter widget (v2.19.1).
    • Grouping rows widget:
    • diff --git a/js/widgets/widget-grouping.js b/js/widgets/widget-grouping.js index 2b7df8f4..fb00d40b 100644 --- a/js/widgets/widget-grouping.js +++ b/js/widgets/widget-grouping.js @@ -1,4 +1,4 @@ -/*! Widget: grouping - updated 9/1/2015 (v2.23.3) *//* +/*! Widget: grouping - updated 10/25/2015 (v2.23.6) *//* * Requires tablesorter v2.8+ and jQuery 1.7+ * by Rob Garrison */ @@ -38,20 +38,53 @@ return txt ? (txt + ' ').substring(0, num) : ''; }, date : function(c, $column, txt, part, group){ - var wo = c.widgetOptions, - time = new Date(txt || ''), - hours = time.getHours(); - return part === 'year' ? time.getFullYear() : - part === 'month' ? wo.group_months[time.getMonth()] : - part === 'monthyear' ? wo.group_months[time.getMonth()] + ' ' + time.getFullYear() : - part === 'day' ? wo.group_months[time.getMonth()] + ' ' + time.getDate() : - part === 'week' ? wo.group_week[time.getDay()] : - part === 'time' ? ('00' + (hours > 12 ? hours - 12 : hours === 0 ? hours + 12 : hours)).slice(-2) + ':' + - ('00' + time.getMinutes()).slice(-2) + ' ' + ('00' + wo.group_time[hours >= 12 ? 1 : 0]).slice(-2) : - wo.group_dateString(time); + var year, month, + wo = c.widgetOptions, + time = new Date(txt || ''); + + // check for valid date + if ( time instanceof Date && isFinite( time ) ) { + year = time.getFullYear(); + month = ts.grouping.findMonth( wo, time.getMonth() ); + return part === 'year' ? year : + part === 'month' ? month : + part === 'monthyear' ? month + ' ' + year : + part === 'day' ? month + ' ' + time.getDate() : + part === 'week' ? ts.grouping.findWeek( wo, time.getDay() ) : + part === 'time' ? ts.grouping.findTime( wo, time ) : + wo.group_dateString( time, c, $column ); + } else { + return wo.group_dateInvalid; + } } }, + // group date type functions to allow using this widget with Globalize + findMonth : function( wo, month ) { + // CLDR returns an object { 1: "Jan", 2: "Feb", 3: "Mar", ..., 12: "Dec" } + return wo.group_months[ month + ( ( wo.group_months[0] || '' ) === '' ? 1 : 0 ) ]; + }, + findWeek : function( wo, day ) { + if ( $.isArray( wo.group_week ) ) { + return wo.group_week[ day ]; + } else if ( !$.isEmptyObject( wo.group_week ) ) { + // CLDR returns { sun: "Sun", mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", ... } + var cldrWeek = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ]; + return wo.group_week[ cldrWeek[ day ] ]; + } + }, + findTime : function( wo, time ) { + var suffix, + h = time.getHours(), + period = h >= 12 ? 1 : 0, + // CLDR returns { am: "AM", pm: "PM", ... } + isObj = wo.group_time.am && wo.group_time.pm, + hours = ( '00' + ( wo.group_time24Hour && h > 12 ? h - 12 : wo.group_time24Hour && h === 0 ? h + 12 : h ) ).slice(-2), + min = ( '00' + time.getMinutes() ).slice(-2); + suffix = wo.group_time[ isObj ? [ 'am', 'pm' ][ period ] : period ]; + return hours + ':' + min + ( wo.group_time24Hour ? '' : ' ' + ( suffix || '' ) ); + }, + update : function(table, c, wo){ if ($.isEmptyObject(c.cache)) { return; } var rowIndex, tbodyIndex, currentGroup, $rows, groupClass, grouping, norm_rows, saveName, direction, @@ -236,6 +269,12 @@ group_months : [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], group_week : [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], group_time : [ 'AM', 'PM' ], + + // use 12 vs 24 hour time + group_time24Hour : false, + // group header text added for invalid dates + group_dateInvalid : 'Invalid Date', + // this function is used when 'group-date' is set to create the date string // you can just return date, date.toLocaleString(), date.toLocaleDateString() or d.toLocaleTimeString() // reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Conversion_getter