- Bug beim Übernehmen eines Termins in die Zeiterfassung, wenn man Stunden als Zeiteinheit ausgewählt hatte, behoben.
- Berichte und Mitarbeiterstundenkonto eingebaut
- Node-Module optimiert (sehr viele gelöscht)
This commit is contained in:
2023-05-15 11:54:13 +02:00
parent b309b7ce0a
commit 88fd24f3a9
27312 changed files with 4294231 additions and 9887486 deletions

44
.gitignore vendored
View File

@@ -593,4 +593,46 @@ obj
/UnitTestProject472/bin
/UnitTestProject472/obj
/UnitTestProject45/bin
/UnitTestProject45/obj
/UnitTestProject45/obj
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/00b5f0d5941249ee88d7a8d45b9fb7e7/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/00b5f0d5941249ee88d7a8d45b9fb7e7/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/3a26bfe04f544c888c3c22c21e050bd9/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/3a26bfe04f544c888c3c22c21e050bd9/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/5e1a7ed7594f4cb8847da1a45cb5673f/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/5e1a7ed7594f4cb8847da1a45cb5673f/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/6f24f6f284934376a0bb9523810927a8/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/6f24f6f284934376a0bb9523810927a8/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/8aff2dde24b04e33ab392c5ca1ee9cdd/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/8aff2dde24b04e33ab392c5ca1ee9cdd/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/52df7b78120346188343ca5e9e5f1fa5/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/52df7b78120346188343ca5e9e5f1fa5/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/72d7034f45aa46498b7c2dbf08bab4f5/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/72d7034f45aa46498b7c2dbf08bab4f5/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/101e4887e6284256a484b71c9791c62a/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/101e4887e6284256a484b71c9791c62a/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/278d0ec2bca24727ba0be74fce4ab7a9/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/278d0ec2bca24727ba0be74fce4ab7a9/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/35014e6626e447e19072ffe87f3fef60/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/35014e6626e447e19072ffe87f3fef60/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/3049467ad6044509a9b73ae6a7cecd20/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/3049467ad6044509a9b73ae6a7cecd20/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/ccb2b088065a484aa0eb9f62d2f9cf27/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/ccb2b088065a484aa0eb9f62d2f9cf27/virtualDocument.prnx
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/e7eac8d4d5db47a799420bfb0d6fbc2f/BuildResultDetails.json
/BeWoPlanerMobil/App_Data/WebDocumentViewerCache/e7eac8d4d5db47a799420bfb0d6fbc2f/virtualDocument.prnx
/BeWoPlanerMobil/demo/temp
/BeWoPlanerMobil/node_modules/.bin/escodegen
/BeWoPlanerMobil/node_modules/.bin/escodegen.cmd
/BeWoPlanerMobil/node_modules/.bin/escodegen.ps1
/BeWoPlanerMobil/node_modules/.bin/esgenerate
/BeWoPlanerMobil/node_modules/.bin/esgenerate.cmd
/BeWoPlanerMobil/node_modules/.bin/esgenerate.ps1
/BeWoPlanerMobil/node_modules/.bin/esparse
/BeWoPlanerMobil/node_modules/.bin/esparse.cmd
/BeWoPlanerMobil/node_modules/.bin/esparse.ps1
/BeWoPlanerMobil/node_modules/.bin/esvalidate
/BeWoPlanerMobil/node_modules/.bin/esvalidate.cmd
/BeWoPlanerMobil/node_modules/.bin/esvalidate.ps1
/BeWoPlanerMobil/node_modules/.bin/pegjs
/BeWoPlanerMobil/node_modules/.bin/pegjs.cmd
/BeWoPlanerMobil/node_modules/.bin/pegjs.ps1

View File

@@ -169,7 +169,7 @@ namespace BeWo.View.Report.Employee
if (auswertungNachMa)
{
if (checkbox_all. IsChecked.Value || checkbox_all.Visibility == Visibility.Hidden)
if (checkbox_all.IsChecked.Value || checkbox_all.Visibility == Visibility.Hidden)
{
_SelectedEmployee = null;
}

View File

@@ -1,70 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Optimization;
namespace BeWoPlanerMobil {
public class DevExtremeBundleConfig {
public static void RegisterBundles(BundleCollection bundles) {
var styleBundle = new StyleBundle("~/Content/DevExtremeBundle");
var scriptBundle = new ScriptBundle("~/Scripts/DevExtremeBundle");
// Adding the UTF-8 charset to display icons correctly
styleBundle.Include("~/Content/Charset.css");
// Uncomment to use the Gantt control
//styleBundle.Include("~/Content/dx-gantt.css");
// Uncomment to use the Diagram control
//styleBundle.Include("~/Content/dx-diagram.css");
styleBundle.Include("~/Content/dx.common.css");
// Predefined themes: https://js.devexpress.com/DevExtreme/Guide/Themes_and_Styles/Predefined_Themes/
styleBundle.Include("~/Content/dx.light.css");
// Uncomment to use the Gantt control
//scriptBundle.Include("~/Scripts/dx-gantt.js");
// Uncomment to use the Diagram control
//scriptBundle.Include("~/Scripts/dx-diagram.js");
// NOTE: jQuery may already be included in the default script bundle. Check the BundleConfig.cs file.
//scriptBundle.Include("~/Scripts/jquery-3.6.0.js");
// Uncomment to use Globalize for localization
// Docs: https://docs.devexpress.com/DevExtremeAspNetMvc/400706#globalize
//scriptBundle.Include("~/Scripts/cldr.js");
//scriptBundle.Include("~/Scripts/cldr/event.js");
//scriptBundle.Include("~/Scripts/cldr/supplemental.js");
//scriptBundle.Include("~/Scripts/cldr/unresolved.js");
//scriptBundle.Include("~/Scripts/globalize.js");
//scriptBundle.Include("~/Scripts/globalize/message.js");
//scriptBundle.Include("~/Scripts/globalize/number.js");
//scriptBundle.Include("~/Scripts/globalize/currency.js");
//scriptBundle.Include("~/Scripts/globalize/date.js");
// Uncomment to enable client-side export
//scriptBundle.Include("~/Scripts/jszip.js");
scriptBundle.Include("~/Scripts/dx.all.js");
// Uncomment to provide geo-data for the VectorMap control
// Docs: https://js.devexpress.com/DevExtreme/Guide/Widgets/VectorMap/Providing_Data/#Data_for_Areas
//scriptBundle.Include("~/Scripts/vectormap-data/world.js");
scriptBundle.Include("~/Scripts/aspnet/dx.aspnet.mvc.js");
scriptBundle.Include("~/Scripts/aspnet/dx.aspnet.data.js");
bundles.Add(styleBundle);
bundles.Add(scriptBundle);
#if !DEBUG
BundleTable.EnableOptimizations = true;
#endif
}
}
}

View File

@@ -1,5 +1,4 @@
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc;
namespace BeWoPlanerMobil
{

View File

@@ -7,9 +7,6 @@ namespace BeWoPlanerMobil
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.MapRoute(
name: "Login",
url: "Login/{tenant}",

File diff suppressed because it is too large Load Diff

View File

@@ -92,11 +92,20 @@ namespace BeWoPlanerMobil.Controllers
return Logout();
}
var mandator = GetMandator();
var mandatorSettings = mandator.Settings;
if(Model.Mandator is null)
{
Model.Mandator = GetMandator();
}
var mandatorSettings = Model.Mandator.Settings;
Model.EinheitZeiterfassung = UserSettingsUtils.GetSettingValueAsInteger(mandatorSettings, SettingsKeys.EinheitZeiterfassung, 0);
if(Model.EinheitZeiterfassung == 1)
{
Model.IsShowingDurationInHours = true;
}
Model.SetStartTimeToEndTimeAfterSave = UserSettingsUtils.GetSettingValueAsBool(mandatorSettings, SettingsKeys.SetStartTimeToEndTimeAfterSave);
var userSettings = AbstractModel.UserSettings;
@@ -243,8 +252,8 @@ namespace BeWoPlanerMobil.Controllers
if(Model.IsZeiterfassungInStdMin)
{
var x = UserSettingsUtils.GetSettingValueAsInteger(userSettings, SettingsKeys.LetzteZeiterfassungsDauer);
Model.IsShowingDurationInHours = x == 1;
var letzteZeiterfassungsdauer = UserSettingsUtils.GetSettingValueAsInteger(userSettings, SettingsKeys.LetzteZeiterfassungsDauer);
Model.IsShowingDurationInHours = letzteZeiterfassungsdauer == 1;
}
}
catch(Exception e)

View File

@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
@@ -12,15 +11,12 @@ using BeWoPlanerMobil.Util;
using BS.Shared;
using BS.Shared.Core;
using BS.Shared.DataContracts;
using DevExpress.CodeParser;
using DevExpress.XtraReports.UI;
namespace BeWoPlanerMobil.Controllers
{
public class ReportViewerController : AbstractBaseController
{
private ReportViewerModel _Model;
public ReportViewerModel Model
@@ -50,6 +46,8 @@ namespace BeWoPlanerMobil.Controllers
public ActionResult ReportViewer()
{
Model.Report = null;
var month = DateTime.Today.Month;
var year = DateTime.Today.Year;
var first = new DateTime(year, month, 1).AddMonths(-1);
@@ -159,11 +157,140 @@ namespace BeWoPlanerMobil.Controllers
var urlSuffix = $"/ReportView.aspx?dcid={MobileSessionFacade.Tenant}queryeoid{Model.Employee.EmployeeOid.Value}&qoid={query.Oid}&type={Utils.EnumName(ReportTypes.QueryReport)}";
#if DEBUG
return $"http://localhost:3777/Host{urlSuffix}";
#endif
return GetSiteOfOrigin() + urlSuffix;
}
return $"{url.Scheme}//{url.Host}{urlSuffix}";
private string GetSiteOfOrigin()
{
if(Model?.Employee?.EmployeeOid is null)
{
return null;
}
var url = Request?.Url;
#if DEBUG
return "http://localhost:3777/Host";
#endif
return $"{url.Scheme}//{url.Host}";
}
[Authorize]
public ActionResult LoadViewerForm(string reportType)
{
if(Model is null)
{
return Logout();
}
Model.SelectedReportType = reportType == "0" ? ReportType.Berichte : ReportType.Mitarbeiterstundenkonto;
return PartialView("ReportViewerFormPartial", Model);
}
[Authorize]
public ActionResult LoadMitarbeiterstundenkonto(string parameters)
{
if(Model?.Employee?.EmployeeOid is null)
{
return Logout();
}
if(!string.IsNullOrWhiteSpace(parameters))
{
var splitParameters = parameters.Split(';');
if(splitParameters.Length == 6)
{
var month = int.Parse(splitParameters[0]);
var year = int.Parse(splitParameters[1]);
var isEmployee = bool.Parse(splitParameters[2]);
var all = bool.Parse(splitParameters[3]);
var oid = long.Parse(splitParameters[4]);
var ansicht = int.Parse(splitParameters[5]);
var siteOfOrigin = GetSiteOfOrigin();
var url = $"{siteOfOrigin}/ReportView.aspx?type={Utils.EnumName(ReportTypes.EmployeeHourReport)}";
if(isEmployee)
{
long? employeeOid = oid;
if(all || !AbstractModel.HasRightMitarbeiterstundenkontoViewAll)
{
employeeOid = null;
}
if(!(employeeOid is null))
{
employeeOid = oid;
}
if(!AbstractModel.HasRightMitarbeiterstundenkontoViewAll)
{
employeeOid = Model.Employee.EmployeeOid;
}
if(employeeOid > 0)
{
url += $"&eoid={employeeOid}";
}
}
else
{
long? teamOid = oid;
if(all || !AbstractModel.HasRightMitarbeiterstundenkontoViewAll)
{
teamOid = null;
}
if(!(teamOid is null))
{
teamOid = oid;
}
url += "&toid=";
if(teamOid > 0 && !all)
{
url += $"{teamOid}";
}
else if(all)
{
url += string.Join(",", Model.AllTeams.Select(team => team.TeamOid));
}
}
url += $"&m={month}&y={year}";
if(ansicht != 0)
{
url += $"&ansicht={ansicht}";
}
var tempToken = DownloadService.CreateTemporaryToken(url, true);
url += $"&token={tempToken}";
var webClient = new WebClient();
var data = webClient.DownloadData(url);
var report = new XtraReport();
using(var memoryStream = new MemoryStream(data))
{
report.PrintingSystem.LoadDocument(memoryStream);
}
Model.Report = report;
}
}
return PartialView("DocumentWebViewerPartial", Model);
}
}
}

View File

@@ -18,7 +18,11 @@ namespace BeWoPlanerMobil
{
protected void Application_Start()
{
DevExtremeBundleConfig.RegisterBundles(BundleTable.Bundles);
// Testweise hinzugefügt, weil die Suche und Download/Export nicht funktioniert. KGW
//DevExpress.XtraReports.Web.WebDocumentViewer.Native.WebDocumentViewerBootstrapper.SessionState = System.Web.SessionState.SessionStateBehavior.Required;
//DevExpress.XtraReports.Web.WebDocumentViewer.DefaultWebDocumentViewerContainer.RegisterWebDocumentViewerDrillThroughProcessor<WebDocumentViewerDrillThroughProcessor>();
//DevExpress.XtraReports.Web.WebDocumentViewer.DefaultWebDocumentViewerContainer.UseFileDocumentStorage(Server.MapPath("~/App_Data/WebDocumentViewerCache"));
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);

View File

@@ -143,5 +143,9 @@ namespace BeWoPlanerMobil.Models
public static bool HasRightToRateGoals => CheckRight(UserRightType.BewertenInZeiterfassung);
public static bool HasRightToEditCustomers => CheckRight(UserRightType.CustomerView_Edit);
public static bool HasRightMitarbeiterstundenkontoViewAll => CheckRight(UserRightType.Mitarbeiterstundenkonto_ViewAll);
public static bool HasRightMitarbeiterstundenkontoViewTeams => CheckRight(UserRightType.Mitarbeiterstundenkonto_ViewTeams);
public static bool HasRightMitarbeiterstundenkontoViewSelf => CheckRight(UserRightType.Mitarbeiterstundenkonto_ViewSelf);
}
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Linq;
using System.Web.Mvc;
using BeWo.View.Navigation.Filter;
@@ -565,7 +566,18 @@ namespace BeWoPlanerMobil.Models
}
}
public string DurationToEdit => SelectedServiceRecord?.RoundedDuration.ToString() ?? string.Empty;
public string DurationToEdit
{
get
{
if(SelectedDurationUnit == "Stunden")
{
return SelectedServiceRecord is null ? string.Empty : (SelectedServiceRecord.RoundedDuration / 60).ToString();
}
return SelectedServiceRecord?.RoundedDuration.ToString() ?? string.Empty;
}
}
public string DistanceToEdit => SelectedServiceRecord?.DistanceInMeter.ToString() ?? string.Empty;
@@ -650,6 +662,9 @@ namespace BeWoPlanerMobil.Models
public DateTime LastSelectedServiceRecordMonth { get; set; }
public int LastSelectedServiceRecordTimeIntervalDays { get; set; }
/// <summary>
/// Zeitraum der Zeiterfassungseintragsliste (z.B. Alle, Letzte 7 Tage, etc.)
/// </summary>
public ServiceRecordTimeInterval ServiceRecordTimeInterval { get; set; }
public int SelectedDayCount { get; set; }
public NullableDateTimeSpan SelectedZeitraum { get; set; }
@@ -710,6 +725,8 @@ namespace BeWoPlanerMobil.Models
}
}
public MandatorDC Mandator { get; set; }
#endregion
}

View File

@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.Mvc;
using BS.Shared.DataContracts;
using BS.Shared.DataContracts.Compact;
@@ -77,6 +78,8 @@ namespace BeWoPlanerMobil.Models
return result;
}
result.Add(new SelectListItem { Text = "", Value = "0" });
foreach(var query in Queries)
{
result.Add(new SelectListItem { Text = query.Title, Value = query.Oid.ToString() });
@@ -100,7 +103,15 @@ namespace BeWoPlanerMobil.Models
return result;
}
foreach(var employee in AllEmployees)
if(HasRightMitarbeiterstundenkontoViewSelf && !HasRightMitarbeiterstundenkontoViewAll)
{
result.Add(new SelectListItem{ Text = Employee.LastNameFirstName, Value = Employee.EmployeeOid.ToString()});
return result;
}
result.Add(new SelectListItem { Text = string.Empty, Value = "0" });
foreach(var employee in AllEmployees.OrderBy(e => e.SimpleDescription))
{
result.Add(new SelectListItem { Text = employee.SimpleDescription, Value = employee.EmployeeOid.ToString() });
}
@@ -123,7 +134,9 @@ namespace BeWoPlanerMobil.Models
return result;
}
foreach(var team in AllTeams)
result.Add(new SelectListItem { Text = string.Empty, Value = "0" });
foreach(var team in AllTeams.OrderBy(t => t.Name))
{
result.Add(new SelectListItem { Text = team.Name, Value = team.TeamOid.ToString() });
}

View File

@@ -1,5 +0,0 @@
/*!
* CLDR JavaScript Library v0.5.4 2020-10-22T15:56Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
!function(e,t){"function"==typeof define&&define.amd?define(t):"object"==typeof module&&"object"==typeof module.exports?module.exports=t():e.Cldr=t()}(this,(function(){var e,t=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},n=function(e,n){if(t(e)&&(e=e.join("/")),"string"!=typeof e)throw new Error('invalid path "'+e+'"');return(e=(e=e.replace(/^\//,"").replace(/^cldr\//,"")).replace(/{[a-zA-Z]+}/g,(function(e){return e=e.replace(/^{([^}]*)}$/,"$1"),n[e]}))).split("/")},r=function(e,t){var n,r;if(e.some)return e.some(t);for(n=0,r=e.length;n<r;n++)if(t(e[n],n,e))return!0;return!1},o=function(e,t,n,o){var a,i=n[0],l=n[1],u=e.localeSep,c=n[2],f=n.slice(3,4);return o=o||{},"und"!==i&&"Zzzz"!==l&&"ZZ"!==c?[i,l,c].concat(f):void 0!==t.get("supplemental/likelySubtags")?r([[i,l,c],[i,c],[i,l],[i],["und",l]],(function(e){return a=!/\b(Zzzz|ZZ)\b/.test(e.join(u))&&t.get(["supplemental/likelySubtags",e.join(u)])}))?(a=a.split(u),["und"!==i?i:a[0],"Zzzz"!==l?l:a[1],"ZZ"!==c?c:a[2]].concat(f)):o.force?t.get("supplemental/likelySubtags/und").split(u):void 0:void 0},a=function(e,t,n){var a,i=n[0],l=n[1],u=n[2],c=n[3];return r([[[i,"Zzzz","ZZ"],[i]],[[i,"Zzzz",u],[i,u]],[[i,l,"ZZ"],[i,l]]],(function(r){var i=o(e,t,r[0]);return a=r[1],i&&i[0]===n[0]&&i[1]===n[1]&&i[2]===n[2]}))?(c&&a.push(c),a):n},i=function(e){var t,n=[];return(t=(e=e.replace(/_/,"-")).split("-u-"))[1]&&(t[1]=t[1].split("-t-"),e=t[0]+(t[1][1]?"-t-"+t[1][1]:""),n[4]=t[1][0]),null===(t=e.split("-t-")[0].match(/^(([a-z]{2,3})(-([A-Z][a-z]{3}))?(-([A-Z]{2}|[0-9]{3}))?)((-([a-zA-Z0-9]{5,8}|[0-9][a-zA-Z0-9]{3}))*)$|^(root)$/))?["und","Zzzz","ZZ"]:(n[0]=t[10]||t[2]||"und",n[1]=t[4]||"Zzzz",n[2]=t[6]||"ZZ",t[7]&&t[7].length&&(n[3]=t[7].slice(1)),n)},l=function(e,t){var n,r;if(e.forEach)return e.forEach(t);for(n=0,r=e.length;n<r;n++)t(e[n],n,e)},u=function(e,t,n){var r=e._availableBundleMap,u=e._availableBundleMapQueue;return u.length&&(l(u,(function(n,l){var c,f,p,s;if(s=i(n),void 0===(f=o(e,t,s)))throw u.splice(l,1),new Error("Could not find likelySubtags for "+n);p=(p=a(e,t,f)).join(e.localeSep),(c=r[p])&&c.length<n.length||(r[p]=n)})),e._availableBundleMapQueue=[]),r[n]||null},c=function(e,t){var n,r;return r=e+(t&&JSON?": "+JSON.stringify(t):""),(n=new Error(r)).code=e,l(function(e){var t,n=[];if(Object.keys)return Object.keys(e);for(t in e)n.push(t);return n}(t),(function(e){n[e]=t[e]})),n},f=function(e,t,n){if(!t)throw c(e,n)},p=function(e,t){f("E_MISSING_PARAMETER",void 0!==e,{name:t})},s=function(e,t,n,r){f("E_INVALID_PAR_TYPE",n,{expected:r,name:t,value:e})},d=function(e,n){s(e,n,"string"==typeof e||t(e),"String or Array")},v=function(e,t){var n;s(e,t,void 0===e||null!==(n=e)&&""+n=="[object Object]","Plain Object")},h=function(e,t){var n,r=e,o=t.length;for(n=0;n<o-1;n++)if(!(r=r[t[n]]))return;return r[t[n]]},g=function(e,t){var n,r=e._availableBundleMapQueue,o=h(t,["main"]);if(o)for(n in o)o.hasOwnProperty(n)&&"root"!==n&&-1===r.indexOf(n)&&r.push(n)},z=function(e){return t(e)?e:[e]},b=e=function(){var n={},r=[].slice.call(arguments,0);return l(r,(function(r){var o;for(o in r)o in n&&"object"==typeof n[o]&&!t(n[o])?n[o]=e(n[o],r[o]):n[o]=r[o]})),n},y=function(e,t,n){var r,o,a;for(p(n[0],"json"),r=0;r<n.length;r++)for(a=z(n[r]),o=0;o<a.length;o++)v(a[o],"json"),t=b(t,a[o]),g(e,a[o]);return t},_=function(e,t,r){var o=n(t,r);return h(e._resolved,o)},Z=function(e){this.init(e)};return Z._alwaysArray=z,Z._coreLoad=y,Z._createError=c,Z._itemGetResolved=_,Z._jsonMerge=b,Z._pathNormalize=n,Z._resourceGet=h,Z._validatePresence=p,Z._validateType=s,Z._validateTypePath=d,Z._validateTypePlainObject=v,Z._availableBundleMap={},Z._availableBundleMapQueue=[],Z._resolved={},Z.localeSep="-",Z.load=function(){Z._resolved=y(Z,Z._resolved,arguments)},Z.prototype.init=function(e){var t,n,r,l,c,f,d,v,h,g,z=Z.localeSep,b="";p(e,"locale"),s(g=e,"locale","string"==typeof g,"a string"),5===(f=i(e)).length&&(b=z+"u"+z+(v=f.pop()),f[3]||f.pop()),h=f[3],n=(r=o(Z,this,f,{force:!0})||f)[0],c=r[1],d=r[2],l=a(Z,this,r).join(z),this.attributes=t={bundle:u(Z,this,l),minLanguageId:l+b,maxLanguageId:r.join(z)+b,language:n,script:c,territory:d,region:d,variant:h},v&&("-"+v).replace(/-[a-z]{3,8}|(-[a-z]{2})-([a-z]{3,8})/g,(function(e,n,r){n?t["u"+n]=r:t["u"+e]=!0})),this.locale=e},Z.prototype.get=function(e){return p(e,"path"),d(e,"path"),_(Z,e,this.attributes)},Z.prototype.main=function(e){return p(e,"path"),d(e,"path"),f("E_MISSING_BUNDLE",null!==this.attributes.bundle,{locale:this.locale}),e=z(e),this.get(["main/{bundle}"].concat(e))},Z}));

View File

@@ -1,11 +0,0 @@
/*!
* CLDR JavaScript Library v0.5.4 2020-10-22T15:56Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
!function(e){"function"==typeof define&&define.amd?define(["../cldr"],e):"object"==typeof module&&"object"==typeof module.exports?module.exports=e(require("../cldr")):e(Cldr)}((function(e){var t,n=e._pathNormalize,r=e._validatePresence,i=e._validateType;
/*!
* EventEmitter v4.2.7 - git.io/ee
* Oliver Caldwell
* MIT license
* @preserve
*/t=function(){function e(){}var t=e.prototype,n={};function r(e,t){for(var n=e.length;n--;)if(e[n].listener===t)return n;return-1}function i(e){return function(){return this[e].apply(this,arguments)}}return t.getListeners=function(e){var t,n,r=this._getEvents();if(e instanceof RegExp)for(n in t={},r)r.hasOwnProperty(n)&&e.test(n)&&(t[n]=r[n]);else t=r[e]||(r[e]=[]);return t},t.flattenListeners=function(e){var t,n=[];for(t=0;t<e.length;t+=1)n.push(e[t].listener);return n},t.getListenersAsObject=function(e){var t,n=this.getListeners(e);return n instanceof Array&&((t={})[e]=n),t||n},t.addListener=function(e,t){var n,i=this.getListenersAsObject(e),s="object"==typeof t;for(n in i)i.hasOwnProperty(n)&&-1===r(i[n],t)&&i[n].push(s?t:{listener:t,once:!1});return this},t.on=i("addListener"),t.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},t.once=i("addOnceListener"),t.defineEvent=function(e){return this.getListeners(e),this},t.defineEvents=function(e){for(var t=0;t<e.length;t+=1)this.defineEvent(e[t]);return this},t.removeListener=function(e,t){var n,i,s=this.getListenersAsObject(e);for(i in s)s.hasOwnProperty(i)&&-1!==(n=r(s[i],t))&&s[i].splice(n,1);return this},t.off=i("removeListener"),t.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},t.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},t.manipulateListeners=function(e,t,n){var r,i,s=e?this.removeListener:this.addListener,o=e?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(r=n.length;r--;)s.call(this,t,n[r]);else for(r in t)t.hasOwnProperty(r)&&(i=t[r])&&("function"==typeof i?s.call(this,r,i):o.call(this,r,i));return this},t.removeEvent=function(e){var t,n=typeof e,r=this._getEvents();if("string"===n)delete r[e];else if(e instanceof RegExp)for(t in r)r.hasOwnProperty(t)&&e.test(t)&&delete r[t];else delete this._events;return this},t.removeAllListeners=i("removeEvent"),t.emitEvent=function(e,t){var n,r,i,s=this.getListenersAsObject(e);for(i in s)if(s.hasOwnProperty(i))for(r=s[i].length;r--;)!0===(n=s[i][r]).once&&this.removeListener(e,n.listener),n.listener.apply(this,t||[])===this._getOnceReturnValue()&&this.removeListener(e,n.listener);return this},t.trigger=i("emitEvent"),t.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},t.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},t._getOnceReturnValue=function(){return!this.hasOwnProperty("_onceReturnValue")||this._onceReturnValue},t._getEvents=function(){return this._events||(this._events={})},e.noConflict=function(){return n.EventEmitter=originalGlobalValue,e},e}();var s,o,u=function(e,t){i(e,t,void 0===e||"function"==typeof e,"Function")},f=new t;function c(e,t){i(e,t,"string"==typeof e||e instanceof RegExp,"String or RegExp")}function a(e,t){return function(n,i){return r(n,"event"),c(n,"event"),r(i,"listener"),u(i,"listener"),t[e].apply(t,arguments)}}function h(e){return a("off",e)}function l(e){return a("on",e)}function p(e){return a("once",e)}function v(){s=e.prototype.get,e.prototype.get=function(e){var t=s.apply(this,arguments);return e=n(e,this.attributes).join("/"),f.trigger("get",[e,t]),this.ee.trigger("get",[e,t]),t}}return e.off=h(f),e.on=l(f),e.once=p(f),o=e.prototype.init,e.prototype.init=function(){var e;this.ee=e=new t,this.off=h(e),this.on=l(e),this.once=p(e),o.apply(this,arguments)},e._eventInit=v,v(),e}));

View File

@@ -1,5 +0,0 @@
/*!
* CLDR JavaScript Library v0.5.4 2020-10-22T15:56Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
!function(e){"function"==typeof define&&define.amd?define(["../cldr"],e):"object"==typeof module&&"object"==typeof module.exports?module.exports=e(require("../cldr")):e(Cldr)}((function(e){var t=e._alwaysArray,a=function(e){var a,r;return(r=(a=function(a){return function(r){return r=t(r),e.get([a].concat(r))}})("supplemental")).weekData=a("supplemental/weekData"),r.weekData.firstDay=function(){return e.get("supplemental/weekData/firstDay/{territory}")||e.get("supplemental/weekData/firstDay/001")},r.weekData.minDays=function(){var t=e.get("supplemental/weekData/minDays/{territory}")||e.get("supplemental/weekData/minDays/001");return parseInt(t,10)},r.timeData=a("supplemental/timeData"),r.timeData.allowed=function(){return e.get("supplemental/timeData/{territory}/_allowed")||e.get("supplemental/timeData/001/_allowed")},r.timeData.preferred=function(){return e.get("supplemental/timeData/{territory}/_preferred")||e.get("supplemental/timeData/001/_preferred")},r},r=e.prototype.init;return e.prototype.init=function(){r.apply(this,arguments),this.supplemental=a(this)},e}));

View File

@@ -1,5 +0,0 @@
/*!
* CLDR JavaScript Library v0.5.4 2020-10-22T15:56Z MIT license © Rafael Xavier
* http://git.io/h4lmVg
*/
!function(e){"function"==typeof define&&define.amd?define(["../cldr"],e):"object"==typeof module&&"object"==typeof module.exports?module.exports=e(require("../cldr")):e(Cldr)}((function(e){var t,o=e._coreLoad,r=e._jsonMerge,n=e._pathNormalize,a=e._resourceGet,i=e._validatePresence,d=e._validateTypePath,u=t=function(e,o,i,d,u){var l,c,f;if(void 0!==o&&o!==u)return l=n(i,d),void 0!==(f=a(e._resolved,l))&&"object"!=typeof f||(void 0===(f=a(e._raw,l))&&(c=function(e,t){var o,r;if("root"!==t)return o=n(["supplemental/parentLocales/parentLocale",t]),(r=a(e._resolved,o)||a(e._raw,o))?r:(r=t.substr(0,t.lastIndexOf(e.localeSep)))||"root"}(e,o),f=t(e,c,i,r(d,{bundle:c}),o)),void 0!==f&&function(e,t,o){var r,n=e,a=t.length;for(r=0;r<a-1;r++)n[t[r]]||(n[t[r]]={}),n=n[t[r]];n[t[r]]=o}(e._resolved,l,f)),f};return e._raw={},e.load=function(){e._raw=o(e,e._raw,arguments)},e.prototype.get=function(t){return i(t,"path"),d(t,"path"),u(e,this.attributes&&this.attributes.bundle||"",t,this.attributes)},e._eventInit&&e._eventInit(),e}));

View File

@@ -1,136 +0,0 @@
/* ***** BEGIN LICENSE BLOCK *****
* Distributed under the BSD license:
*
* Copyright (c) 2010, Ajax.org B.V.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ***** END LICENSE BLOCK ***** */
/**
* The main class required to set up an Ace instance in the browser.
*
* @class Ace
**/
define(function(require, exports, module) {
"use strict";
require("./lib/fixoldbrowsers");
var dom = require("./lib/dom");
var event = require("./lib/event");
var Range = require("./range").Range;
var Editor = require("./editor").Editor;
var EditSession = require("./edit_session").EditSession;
var UndoManager = require("./undomanager").UndoManager;
var Renderer = require("./virtual_renderer").VirtualRenderer;
// The following require()s are for inclusion in the built ace file
require("./worker/worker_client");
require("./keyboard/hash_handler");
require("./placeholder");
require("./multi_select");
require("./mode/folding/fold_mode");
require("./theme/textmate");
require("./ext/error_marker");
exports.config = require("./config");
/**
* Provides access to require in packed noconflict mode
* @param {String} moduleName
* @returns {Object}
**/
exports.require = require;
if (typeof define === "function")
exports.define = define;
/**
* Embeds the Ace editor into the DOM, at the element provided by `el`.
* @param {String | DOMElement} el Either the id of an element, or the element itself
* @param {Object } options Options for the editor
*
**/
exports.edit = function(el, options) {
if (typeof el == "string") {
var _id = el;
el = document.getElementById(_id);
if (!el)
throw new Error("ace.edit can't find div #" + _id);
}
if (el && el.env && el.env.editor instanceof Editor)
return el.env.editor;
var value = "";
if (el && /input|textarea/i.test(el.tagName)) {
var oldNode = el;
value = oldNode.value;
el = dom.createElement("pre");
oldNode.parentNode.replaceChild(el, oldNode);
} else if (el) {
value = el.textContent;
el.innerHTML = "";
}
var doc = exports.createEditSession(value);
var editor = new Editor(new Renderer(el), doc, options);
var env = {
document: doc,
editor: editor,
onResize: editor.resize.bind(editor, null)
};
if (oldNode) env.textarea = oldNode;
event.addListener(window, "resize", env.onResize);
editor.on("destroy", function() {
event.removeListener(window, "resize", env.onResize);
env.editor.container.env = null; // prevent memory leak on old ie
});
editor.container.env = editor.env = env;
return editor;
};
/**
* Creates a new [[EditSession]], and returns the associated [[Document]].
* @param {Document | String} text {:textParam}
* @param {TextMode} mode {:modeParam}
*
**/
exports.createEditSession = function(text, mode) {
var doc = new EditSession(text, mode);
doc.setUndoManager(new UndoManager());
return doc;
};
exports.Range = Range;
exports.Editor = Editor;
exports.EditSession = EditSession;
exports.UndoManager = UndoManager;
exports.VirtualRenderer = Renderer;
exports.version = exports.config.version;
});

View File

@@ -1,6 +0,0 @@
{
"directory": "external",
"scripts": {
"postinstall": "node ./node_modules/cldr-data-downloader/bin/download.js -i external/cldr-data/index.json -o external/cldr-data/"
}
}

View File

@@ -1,6 +0,0 @@
/dist/.build/
/examples/
/external/
/src/build/
/test/compiler/_compiled/
/tmp/

View File

@@ -1,41 +0,0 @@
{
"root": true,
"extends": "jquery",
"rules": {
"lines-around-comment": ["error", { "ignorePattern": "falls through" }],
"space-in-parens": "off"
},
"overrides": [
{
"files": [
"script/**/*.js"
],
"extends": "jquery",
"env": {
"node": true
}
},
{
"files": [
"dist/**/*.js"
],
"env": {
"amd": true,
"node": true
},
"globals": {
"Cldr": "readonly",
"Globalize": "readonly"
},
"rules": {
"array-bracket-spacing": "off",
"computed-property-spacing": "off",
"max-len": "off",
"no-multiple-empty-lines": "off",
"no-nested-ternary": "off",
"no-unused-vars": "off",
"wrap-iife": "off"
}
}
]
}

View File

@@ -1,5 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto
# JS files must always use LF for tools to work
*.js eol=lf

View File

@@ -1,7 +0,0 @@
.sizecache.json
.tmp-globalize-webpack/
dist/.build/
external/
node_modules/
tmp/
test/compiler/_compiled/

View File

@@ -1,10 +0,0 @@
Andreas Blixt <me@blixt.org>
Boris Moore <BorisMoore@gmail.com>
Dave Reed <dareed@microsoft.com>
Ed Sanders <ejsanders@gmail.com>
Fredrik Blomqvist <fblomqvist@gmail.com>
John Resig <jeresig@gmail.com>
Jörn Zaefferer <joern.zaefferer@gmail.com>
Richard D. Worth <rdworth@gmail.com>
Riku Nieminen <rikunieminen@gmail.com>
Stephen Walther <Swalther@Microsoft.com>

View File

@@ -1,9 +0,0 @@
language: node_js
node_js:
- '12'
before_install:
- npm install -g bower
install:
- npm install
- npm ls || echo # Avoid that `npm ls` aborts
- bower install

View File

@@ -1,85 +0,0 @@
Authors ordered by number of contributions
Rafael Xavier de Souza <rxaviers@gmail.com>
Richard D. Worth <rdworth@gmail.com>
Eric Bréchemier <legalbox@eric.brechemier.name>
Jörn Zaefferer <joern.zaefferer@gmail.com>
Dave Reed <dareed@microsoft.com>
Nikolaus Graf <nik@deck.cc>
Timo Tijhof <krinklemail@gmail.com>
Scott González <scott.gonzalez@gmail.com>
Nick Schonning <nschonni@gmail.com>
Kyle Florence <kyle.florence@gmail.com>
Nova Patch <patch.nova@gmail.com>
Manraj Singh <manrajsinghgrover@gmail.com>
Tobie Langel <tobie.langel@gmail.com>
Nikola Kovacs <nikola.kovacs@gmail.com>
Rob Garrison <wowmotty@gmail.com>
John Reilly <johnny_reilly@hotmail.com>
hmizutanitsi <hmizutanitsi@gmail.com>
shivijais <shivijais16@gmail.com>
Pavel Karoukin <pavel@karoukin.us>
Karan Sharma <karan1276@gmail.com>
Andrew Lunny <alunny@twitter.com>
Wes Cravens <wesley.r.cravens@gmail.com>
Michael Birtwell <michael.birtwell@starleaf.com>
Kris Borchers <kris.borchers@gmail.com>
Yasuhiro Yoshida <yasuhiro.yoppu@gmail.com>
Oleg Gulverdashvili <ctapbiumabp@gmail.com>
Sean Cady <sean.cady@ge.com>
Andrey Stukalin <apstukalin@gmail.com>
Éric Hernández <65465670+OfficialURL@users.noreply.github.com>
Georgi Tsaklev <morwoen@users.noreply.github.com>
Daniel Friesen <d@danf.ca>
robaw <38808938+robaw@users.noreply.github.com>
Ashish Shubham <ashubham@gmail.com>
Phillip Wills <willsp@amazon.com>
FND <FND@users.noreply.github.com>
Edward Salter <EdwardSalter@users.noreply.github.com>
Matt York <york.matt@gmail.com>
Gethin Webster <gethin.webster@agilityworks.co.uk>
gingerbbm <gingerbbm@users.noreply.github.com>
z.ky <zky829@users.noreply.github.com>
Jac <jacalata@users.noreply.github.com>
Adam Brons <ambrons@gmail.com>
Christian Tellnes <christian@tellnes.no>
Alex Sexton <alexsexton@gmail.com>
Kemal Ahmed <goatandsheep@users.noreply.github.com>
Katie Sievert <ksievert@twitter.com>
Manikandan, Ramalingam Kandaswamy <rajavelmani@gmail.com>
Zack Birkenbuel <zack.birkenbuel@hbo.com>
Reza Payami <reza_payami@yahoo.com>
Artur Eshenbrener <strate@yandex.ru>
Marat Dyatko <marat.dyatko@klarna.com>
Retsam <Retsam@users.noreply.github.com>
Devang Negandhi <devangnegandhi@gmail.com>
manj <nikita.melnikov.fw@gmail.com>
Grégoire Castre <castre@doxense.com>
Lee Nave <github-navels@sneakemail.com>
Brahim Arkni <brahim.arkni@gmail.com>
Amanpreet Singh <apsdehal@gmail.com>
Oleg Gaidarenko <markelog@gmail.com>
Isaac Durazo <isaacdurazo@gmail.com>
Ed Sanders <ejsanders@gmail.com>
Kevin Kirsche <Kev.Kirsche+GitHub@gmail.com>
Tobias Nießen <tniessen@tnie.de>
Arvind Kalyan <arvchamp@gmail.com>
Juan Soto <juansoto@fastmail.fm>
Luke Page <luke.a.page@gmail.com>
Mateusz Bożyk <mateusz.bozyk@gmail.com>
Arthur Verschaeve <contact@arthurverschaeve.be>
Riku Nieminen <rikunieminen@gmail.com>
Anne-Gaelle Colom <coloma@westminster.ac.uk>
Raphael Amorim <rapha850@gmail.com>
Peter Dave Hello <hsu@peterdavehello.org>
Bao Ngo <bingo@planwise.com>
Leonardo Balter <leonardo.balter@gmail.com>
Andreas Blixt <me@blixt.org>
Tomasz Peczek <tpeczek@gmail.com>
Robert Plummer <robertleeplummerjr@gmail.com>
Fredrik Blomqvist <fblomqvist@gmail.com>
Christian Vuerings <vueringschristian@gmail.com>
David De Sloovere <david.desloovere@hotmail.com>
Boris Moore <BorisMoore@gmail.com>
John Resig <jeresig@gmail.com>
Stephen Walther <Swalther@Microsoft.com>

View File

@@ -1,5 +0,0 @@
Welcome! Thanks for your interest in contributing to Globalize. More information on how to contribute to this and all other jQuery Foundation projects is over at [contribute.jquery.org](http://contribute.jquery.org). Before writing code for this project, be sure to read [Writing Code for jQuery Foundation Projects](http://contribute.jquery.org/code/).
You may also want to take a look at our [commit & pull request guide](http://contribute.jquery.org/commits-and-pull-requests/) and [style guides](http://contribute.jquery.org/style-guide/) for instructions on how to maintain your fork and submit your code. Before we can merge any pull request, we'll also need you to sign our [contributor license agreement](http://contribute.jquery.org/cla).
You can find us on [Slack](https://globalizejs.slack.com/). If you're new, [join here](https://join.slack.com/t/globalizejs/shared_invite/enQtMjk4OTUwNzM1Nzk0LTk2YmY0YjY3Yzk4YzU3M2NkMDZjNThlNzcwNTkyNGJhNDhiNjdkMWUyN2Q2MjVmNTk0ZjkyNGQ3MWEyNzNmMWU). If you've never contributed to open source before, we've put together [a short guide with tips, tricks, and ideas on getting started](http://contribute.jquery.org/open-source/).

View File

@@ -1,655 +0,0 @@
/* eslint-env node */
module.exports = function( grunt ) {
"use strict";
var isConnectTestRunning,
rdefineEnd = /\}\);[^}\w]*$/,
pkg = grunt.file.readJSON( "package.json" );
function camelCase( input ) {
return input.toLowerCase().replace( /[-/](.)/g, function( _match, group1 ) {
return group1.toUpperCase();
});
}
function mountFolder( connect, path ) {
return connect.static( require( "path" ).resolve( path ) );
}
function replaceConsts( content ) {
return content
// Replace Version
.replace( /@VERSION/g, pkg.version )
// Replace Date yyyy-mm-ddThh:mmZ
.replace( /@DATE/g, ( new Date() ).toISOString().replace( /:\d+\.\d+Z$/, "Z" ) );
}
grunt.initConfig({
pkg: pkg,
authors: {
order: "count"
},
commitplease: {
last: {
options: {
committish: "-n 2"
}
}
},
connect: {
options: {
port: 9001,
hostname: "localhost"
},
test: {
options: {
middleware: function( connect ) {
return [
mountFolder( connect, "." ),
mountFolder( connect, "test" )
];
}
}
},
keepalive: {
options: {
keepalive: true,
middleware: function( connect ) {
return [
mountFolder( connect, "." )
];
}
}
}
},
eslint: {
main: ".",
dist: "dist/"
},
mochaTest: {
test: {
options: {
reporter: "spec"
},
src: [ "test/compiler/*.js" ]
}
},
qunit: {
functional: {
options: {
urls: [
// Use es5-shim here due to .bind(), which is not present on phantomjs v1.9.
// But, it should be on v2.x.
"http://localhost:<%= connect.options.port %>/functional-es5-shim.html"
]
}
},
unit: {
options: {
urls: [ "http://localhost:<%= connect.options.port %>/unit.html" ]
}
}
},
requirejs: {
options: {
dir: "dist/.build",
appDir: "src",
baseUrl: ".",
optimize: "none",
paths: {
cldr: "../external/cldrjs/dist/cldr",
"make-plural": "../external/make-plural/make-plural",
messageformat: "../external/messageformat/messageformat",
"zoned-date-time": "../node_modules/zoned-date-time/src/zoned-date-time"
},
shim: {
"zoned-date-time": {
exports: "ZonedDateTime"
}
},
skipSemiColonInsertion: true,
skipModuleInsertion: true,
// Strip all definitions generated by requirejs.
// Convert content as follows:
// a) "Single return" means the module only contains a return statement that is
// converted to a var declaration.
// b) "Module" means the define wrappers are removed, but content is untouched.
// Only for root id's (the ones in src, not in src's subpaths). Note there's no
// conditional code checking for this type.
onBuildWrite: function( id, _path, contents ) {
var messageformat,
name = camelCase( id.replace( /util\/|common\//, "" ) );
// MakePlural
if ( ( /make-plural/ ).test( id ) ) {
return contents
// Remove browserify wrappers.
.replace( /^\(function\(f\){if\(typeof exports==="object"&&type.*/, "" )
.replace( /\},\{\}\]\},\{\},\[1\]\)\(1\)[\s\S]*?$/, "" )
// Remove browserify exports.
.replace( /Object.defineProperty\(exports[\s\S]*?\n}\);/, "" )
.replace( "exports['default'] = MakePlural;", "" )
.replace( "module.exports = exports['default'];", "" )
// Remove self-tests.
.replace( /var Tests =[\s\S]*?\n}\)\(\);/, "" )
.replace( "this.tests = new Tests(this);", "" )
.replace( /this.fn.test =[\s\S]*?bind\(this\);/, "" )
.replace( "this.tests.add(type, cat, examples);", "" )
// Remove load method.
.replace( /load: \{[\s\S]*?\n \}/, "" )
// Replace its wrapper into var assignment.
.replace( /\(function \(global\) \{/, [
"var MakePlural;",
"/* eslint-disable */",
"MakePlural = (function() {"
].join( "\n" ) )
.replace( /if \(\(typeof module !== 'undefined'[\s\S]*/, [
"return MakePlural;",
"}());",
"/* eslint-enable */"
].join( "\n" ) )
// Wrap everything into a var assignment.
.replace( /^/, [
"var MakePlural;",
"/* eslint-disable */",
"MakePlural = (function() {"
].join( "\n" ) )
.replace( /$/, [
"return MakePlural;",
"}());",
"/* eslint-enable */"
].join( "\n" ) );
// messageformat
} else if ( ( /messageformat/ ).test( id ) ) {
return contents
// Remove browserify wrappers.
.replace( /^\(function\(f\)\{if\(typeof exports==="object"&&type.*/, "" )
.replace( "},{}],2:[function(require,module,exports){", "" )
.replace( /\},\{"\.\/messageformat-parser":1,"make-plural\/plural.*/, "" )
.replace( /\},\{\}\]\},\{\},\[2\]\)\(2\)[\s\S]*?$/, "" )
// Set `MessageFormat.plurals` and remove `make-plural/plurals`
// completely. This is populated by Globalize on demand.
.replace( /var _cp = \[[\s\S]*?$/, "" )
.replace(
"MessageFormat.plurals = require('make-plural/plurals')",
"MessageFormat.plurals = {}"
)
// Set `MessageFormat._parse`
.replace(
"MessageFormat._parse = require('./messageformat-parser').parse;",
""
)
.replace( /module\.exports = \(function\(\) \{([\s\S]*?)\n\}\)\(\);/, [
"MessageFormat._parse = (function() {",
"$1",
"}()).parse;"
].join( "\n" ) )
// Remove unused code.
.replace( /if \(!pluralFunc\) \{\n[\s\S]*?\n \}/, "" )
.replace( /if \(!locale\) \{\n[\s\S]*? \}\n/, "this.lc = [locale];" )
.replace( /(MessageFormat\.formatters) = \{[\s\S]*?\n\};/, "$1 = {};" )
.replace( /MessageFormat\.prototype\.setIntlSupport[\s\S]*?\n\};/, "" )
// Wrap everything into a var assignment.
.replace( "module.exports = MessageFormat;", "" )
.replace( /^/, [
"var MessageFormat;",
"/* eslint-disable */",
"MessageFormat = (function() {"
].join( "\n" ) )
.replace( /$/, [
"return MessageFormat;",
"}());",
"/* eslint-enable */"
].join( "\n" ) );
// message-runtime
} else if ( ( /message-runtime/ ).test( id ) ) {
messageformat = require( "./external/messageformat/messageformat" );
delete messageformat.prototype.runtime.fmt;
delete messageformat.prototype.runtime.pluralFuncs;
contents = contents.replace( "Globalize._messageFormat = {};", [
"/* eslint-disable */",
"Globalize._messageFormat = (function() {",
messageformat.prototype.runtime.toString(),
"return {number: number, plural: plural, select: select};",
"}());",
"/* eslint-enable */"
].join( "\n" ) );
// ZonedDateTime
} else if ( ( /zoned-date-time/ ).test( id ) ) {
contents = contents.replace(
"if (typeof module !== \"undefined\" && module.exports) {\n" +
" module.exports = ZonedDateTime;\n}",
"return ZonedDateTime;"
);
contents = "var ZonedDateTime = (function() {\n" + contents + "}());";
}
// 1, and 2: Remove define() wrap.
// 3: Remove empty define()'s.
contents = contents
.replace( /define\([^{]*?\{/, "" ) /* 1 */
.replace( rdefineEnd, "" ) /* 2 */
.replace( /define\(\[[^\]]+\]\)[\W\n]+$/, "" ); /* 3 */
// Type b (not as simple as a single return)
if ( [ "expand-pattern/augment-format" ].indexOf( id ) !== -1 ) {
contents = "var " + name + " = (function() {" + contents + "}());";
// Type a (single return)
} else if ( ( /\// ).test( id ) ) {
contents = contents
.replace( /\nreturn/, "\nvar " + name + " =" );
}
return contents;
}
},
bundle: {
options: {
modules: [
{
name: "globalize",
include: [ "core" ],
exclude: [ "cldr", "cldr/event" ],
create: true,
override: {
wrap: {
startFile: "src/build/intro-core.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.currency",
include: [ "currency" ],
exclude: [
"cldr",
"cldr/event",
"cldr/supplemental",
"./core",
"./number"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-currency.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.date",
include: [ "date" ],
exclude: [
"cldr",
"cldr/event",
"cldr/supplemental",
"./core",
"./number"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-date.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.message",
include: [ "message" ],
exclude: [ "cldr", "./core" ],
create: true,
override: {
wrap: {
startFile: "src/build/intro-message.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.number",
include: [ "number" ],
exclude: [
"cldr",
"cldr/event",
"cldr/supplemental",
"./core"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-number.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.plural",
include: [ "plural" ],
exclude: [
"cldr",
"cldr/event",
"cldr/supplemental",
"./core"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-plural.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.relative-time",
include: [ "relative-time" ],
exclude: [
"cldr",
"cldr/event",
"cldr/supplemental",
"./core",
"./number",
"./plural"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-relative-time.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.unit",
include: [ "unit" ],
exclude: [
"cldr",
"./core",
"./number",
"./plural"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-unit.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize-runtime",
include: [ "core-runtime" ],
create: true,
override: {
wrap: {
startFile: "src/build/intro-core-runtime.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.currency-runtime",
include: [ "currency-runtime" ],
exclude: [
"./core-runtime",
"./number-runtime"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-currency-runtime.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.date-runtime",
include: [ "date-runtime" ],
exclude: [
"./core-runtime",
"./number-runtime"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-date-runtime.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.message-runtime",
include: [ "message-runtime" ],
exclude: [ "./core-runtime" ],
create: true,
override: {
wrap: {
startFile: "src/build/intro-message-runtime.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.number-runtime",
include: [ "number-runtime" ],
exclude: [
"./core-runtime"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-number-runtime.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.plural-runtime",
include: [ "plural-runtime" ],
exclude: [
"./core-runtime"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-plural-runtime.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.relative-time-runtime",
include: [ "relative-time-runtime" ],
exclude: [
"./core-runtime",
"./number-runtime",
"./plural-runtime"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-relative-time-runtime.js",
endFile: "src/build/outro.js"
}
}
},
{
name: "globalize.unit-runtime",
include: [ "unit-runtime" ],
exclude: [
"./core-runtime",
"./number-runtime",
"./plural-runtime"
],
create: true,
override: {
wrap: {
startFile: "src/build/intro-unit-runtime.js",
endFile: "src/build/outro.js"
}
}
}
]
}
}
},
watch: {
files: [ "src/*.js", "test/functional/**/*.js", "test/unit/**/*.js", "test/*.html" ],
tasks: [ "default" ]
},
copy: {
options: {
processContent: function( content ) {
// Remove leftover define created during rjs build
content = content.replace( /define\(".*/, "" );
// Embed VERSION and DATE
return replaceConsts( content );
}
},
coreAndRuntime: {
expand: true,
cwd: "dist/.build/",
src: [ "globalize.js", "globalize-runtime.js" ],
dest: "dist/"
},
modules: {
expand: true,
cwd: "dist/.build/",
src: [ "globalize*.js", "!globalize.js", "!*runtime*.js" ],
dest: "dist/globalize",
rename: function( dest, src ) {
return require( "path" ).join( dest, src.replace( /globalize\./, "" ) );
}
},
runtimeModules: {
expand: true,
cwd: "dist/.build/",
src: [ "globalize.*runtime.js" ],
dest: "dist/globalize-runtime",
rename: function( dest, src ) {
return require( "path" ).join( dest, src.replace( /(globalize\.|-runtime)/g, "" ) );
}
},
allInOneNode: {
src: "src/build/node-main.js",
dest: "dist/node-main.js"
}
},
uglify: {
options: {
banner: replaceConsts( grunt.file.read( "src/build/intro.min.js" ) )
},
dist: {
files: {
"tmp/globalize.min.js": [ "dist/globalize.js" ],
"tmp/globalize/currency.min.js": [ "dist/globalize/currency.js" ],
"tmp/globalize/date.min.js": [ "dist/globalize/date.js" ],
"tmp/globalize/number.min.js": [ "dist/globalize/number.js" ],
"tmp/globalize/plural.min.js": [ "dist/globalize/plural.js" ],
"tmp/globalize/message.min.js": [ "dist/globalize/message.js" ],
"tmp/globalize/relative-time.min.js": [ "dist/globalize/relative-time.js" ],
"tmp/globalize/unit.min.js": [ "dist/globalize/unit.js" ],
"tmp/globalize-runtime.min.js": [ "dist/globalize-runtime.js" ],
"tmp/globalize-runtime/currency.min.js": [
"dist/globalize-runtime/currency.js"
],
"tmp/globalize-runtime/date.min.js": [ "dist/globalize-runtime/date.js" ],
"tmp/globalize-runtime/message.min.js": [ "dist/globalize-runtime/message.js" ],
"tmp/globalize-runtime/number.min.js": [ "dist/globalize-runtime/number.js" ],
"tmp/globalize-runtime/plural.min.js": [ "dist/globalize-runtime/plural.js" ],
"tmp/globalize-runtime/relative-time.min.js": [
"dist/globalize-runtime/relative-time.js"
],
"tmp/globalize-runtime/unit.min.js": [ "dist/globalize-runtime/unit.js" ]
}
}
},
// TODO figure out how to specify exceptions for externals
"compare_size": {
files: [
"tmp/globalize.min.js",
"tmp/globalize/*min.js",
"tmp/globalize-runtime.min.js",
"tmp/globalize-runtime/*min.js"
],
options: {
compress: {
gz: function( fileContents ) {
return require( "gzip-js" ).zip( fileContents, {}).length;
}
}
}
},
clean: {
dist: [
"dist"
]
},
checkDependencies: {
bower: {
options: {
packageManager: "bower"
}
},
npm: {
options: {
packageManager: "npm"
}
}
}
});
require( "matchdep" ).filterDev( "grunt-*" ).forEach( grunt.loadNpmTasks );
grunt.registerTask( "test", function() {
var args = [].slice.call( arguments );
if ( !isConnectTestRunning ) {
grunt.task.run( "checkDependencies" );
grunt.task.run( "connect:test" );
isConnectTestRunning = true;
}
grunt.task.run( [ "qunit" ].concat( args ).join( ":" ) );
});
// Default task.
grunt.registerTask( "default", [
"eslint:main",
"test:unit",
"clean",
"requirejs",
"copy",
"eslint:dist",
"test:functional",
"mochaTest",
"uglify",
"compare_size",
"commitplease"
]);
};

View File

@@ -1,20 +0,0 @@
Copyright OpenJS Foundation and other contributors, https://openjsf.org
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,818 +0,0 @@
# Globalize
[![Build Status](https://secure.travis-ci.org/globalizejs/globalize.svg?branch=master)](http://travis-ci.org/globalizejs/globalize)
[![devDependency Status](https://david-dm.org/globalizejs/globalize/status.svg)](https://david-dm.org/globalizejs/globalize#info=dependencies)
[![devDependency Status](https://david-dm.org/globalizejs/globalize/dev-status.svg)](https://david-dm.org/globalizejs/globalize#info=devDependencies)
A JavaScript library for internationalization and localization that leverage the official [Unicode CLDR](http://cldr.unicode.org/) JSON data. The library works both for the browser and as a
Node.js module.
- [About Globalize](#about-globalize)
- [Why globalization?](#why-globalization)
- [Why Globalize?](#why-globalize)
- [Migrating from Globalize 0.x](#migrating-from-globalize-0x)
- [Where to use it?](#where-to-use-it)
- [Where does the data come from?](#where-does-the-data-come-from)
- [Only load and use what you need](#pick-the-modules-you-need)
- [Browser support](#browser-support)
- [Getting started](#getting-started)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
- [Performance](#performance)
- [Compilation and the Runtime modules](#compilation-and-the-runtime-modules)
- [Examples](#examples)
- [Community](#community)
- [API](#api)
- [Core](#core-module)
- [Date module](#date-module)
- [Message module](#message-module)
- [Number module](#number-module)
- [Currency module](#currency-module)
- [Plural module](#plural-module)
- [Relative time module](#relative-time-module)
- [Unit module](#unit-module)
- more to come...
- [Error reference](#error-reference)
- [Contributing](#contributing)
- [Roadmap](#roadmap)
- [Development](#development)
- [File structure](#file-structure)
- [Source files](#source-files)
- [Tests](#tests)
- [Build](#build)
## About Globalize
### Why globalization?
Each language, and the countries that speak that language, have different expectations when it comes to how numbers (including currency and percentages) and dates should appear. Obviously, each language has different names for the days of the week and the months of the year. But they also have different expectations for the structure of dates, such as what order the day, month and year are in. In number formatting, not only does the character used to delineate number groupings and the decimal portion differ, but the placement of those characters differ as well.
A user using an application should be able to read and write dates and numbers in the format they are accustomed to. This library makes this possible, providing an API to convert user-entered number and date strings - in their own format - into actual numbers and dates, and conversely, to format numbers and dates into that string format.
Even if the application deals only with the English locale, it may still need globalization to format programming language bytes into human-understandable language and vice-versa in an effective and reasonable way. For example, to display something better than "Edited 1 minutes ago".
### Why Globalize?
Globalize provides number formatting and parsing, date and time formatting and parsing, currency formatting, message formatting (ICU message format pattern), and plural support.
Design Goals.
- Leverages the Unicode CLDR data and follows its UTS#35 specification.
- Keeps code separate from i18n content. Doesn't host or embed any locale data in the library. Empowers developers to control the loading mechanism of their choice.
- Allows developers to load as much or as little data as they need. Avoids duplicating data if using multiple i18n libraries that leverage CLDR.
- Keeps code modular. Allows developers to load the i18n functionalities they need.
- Runs in browsers and Node.js, consistently across all of them.
- Makes globalization as easy to use as jQuery.
Globalize is based on the Unicode Consortium's Common Locale Data Repository (CLDR), the largest and most extensive standard repository of locale data available. CLDR is constantly updated and is used by many large applications and operating systems, so you'll always have access to the most accurate and up-to-date locale data.
Globalize needs CLDR content to function properly, although it doesn't embed, hard-code, or host such content. Instead, Globalize empowers developers to load CLDR data the way they want. Vanilla CLDR in its official JSON format (no pre-processing) is expected to be provided. As a consequence, (a) Globalize avoids bugs caused by outdated i18n content. Developers can use up-to-date CLDR data directly from Unicode as soon as it's released, without having to wait for any pipeline on our side. (b) Developers have full control over which locale coverage they want to provide on their applications. (c) Developers are able to share the same i18n dataset between Globalize and other libraries that leverage CLDR. There's no need for duplicating data.
Globalize is systematically tested against desktop and mobile browsers and Node.js. So, using it you'll get consistent results across different browsers and across browsers and the server.
Globalize doesn't use native Ecma-402 yet, which could potentially improve date and number formatting performance. Although Ecma-402 support is improving among modern browsers and even Node.js, the functionality and locale coverage level varies between different environments (see Comparing JavaScript Libraries [slide 25][]). Globalize needs to do more research and testings to use it reliably.
For alternative libraries and more, check out this [JavaScript globalization overview][].
[slide 25]: http://jsi18n.com/jsi18n.pdf
[JavaScript globalization overview]: http://rxaviers.github.io/javascript-globalization/
### Migrating from Globalize 0.x
Are you coming from Globalize 0.x? Read our [migration guide][] to learn what have changed and how to migrate older 0.x code to up-to-date 1.x.
[migration guide]: doc/migrating-from-0.x.md
### Where to use it?
Globalize is designed to work both in the [browser](#browser-support), or in [Node.js](#usage). It supports both [AMD](#usage) and [CommonJS](#usage).
### Where does the data come from?
Globalize uses the [Unicode CLDR](http://cldr.unicode.org/), the largest and most extensive standard repository of locale data.
We do NOT embed any i18n data within our library. However, we make it really easy to use. Read [How to get and load CLDR JSON data](#2-cldr-content) for more information on its usage.
### Pick the modules you need
| File | Minified + gzipped size | Runtime minified + gzipped size | Summary |
| -------------------------- | ----------------------: | ------------------------------: | ------------------------------------------------------------ |
| globalize.js | 1.7KB | 1.1KB | [Core library](#core-module) |
| globalize/currency.js | 3.0KB | 0.7KB | [Currency module](#currency-module) provides currency formatting |
| globalize/date.js | 7.7KB | 4.3KB | [Date module](#date-module) provides date formatting and parsing |
| globalize/message.js | 5.3KB | 0.7KB | [Message module](#message-module) provides ICU message format support |
| globalize/number.js | 4.4KB | 2.6KB | [Number module](#number-module) provides number formatting and parsing |
| globalize/plural.js | 2.3KB | 0.4KB | [Plural module](#plural-module) provides pluralization support |
| globalize/relative-time.js | 0.8KB | 0.5KB | [Relative time module](#relative-time-module) provides relative time formatting support |
| globalize/unit.js | 0.9KB | 0.6KB | [Unit module](#unit-module) provides unit formatting support |
### Browser Support
Globalize 1.x supports the following browsers:
- Chrome: (Current - 1) or Current
- Firefox: (Current - 1) or Current
- Safari: 5.1+
- Opera: 12.1x, (Current - 1) or Current
- IE9+
*(Current - 1)* or *Current* denotes that we support the current stable version of the browser and the version that preceded it. For example, if the current version of a browser is 24.x, we support the 24.x and 23.x versions.
## Getting Started
npm install globalize cldr-data iana-tz-data
```js
var Globalize = require( "globalize" );
Globalize.load( require( "cldr-data" ).entireSupplemental() );
Globalize.load( require( "cldr-data" ).entireMainFor( "en", "es" ) );
Globalize.loadTimeZone( require( "iana-tz-data" ) );
Globalize("en").formatDate(new Date());
// > "11/27/2015"
Globalize("es").formatDate(new Date());
// > "27/11/2015"
```
Note `cldr-data` is an optional module, read [CLDR content](#2-cldr-content) section below for more information on how to get CLDR from different sources.
The [`iana-tz-data`](https://github.com/rxaviers/iana-tz-data) module is only needed when IANA time zones (via `options.timeZone`) are used with date functions. Read [IANA time zone data](#3-iana-time-zone-data) below for more information.
Read the [Locales section](#locales) for more information about supported locales. For AMD, bower and other usage examples, see [Examples section](#examples).
### Installation
#### Downloading a ZIP or tarball archive
Click the GitHub [releases tab](https://github.com/globalizejs/globalize/releases) and download the latest available Globalize package.
#### Using a package manager
You can use either npm or bower:
- `npm install globalize`
- `bower install globalize`
#### Building from source
1. `git clone https://github.com/globalizejs/globalize.git`
2. [Build the distribution files](#build)
### Requirements
#### 1. Dependencies
If you use module loading like ES6 import, CommonJS, or AMD and fetch your code using package managers like *npm* or *bower*, you don't need to worry about this and can skip reading this section. Otherwise, you need to satisfy Globalize dependencies prior to using it. There is only one external dependency: [cldr.js][], which is a CLDR low level manipulation tool. Additionally, you need to satisfy the cross-dependencies between modules.
| Module | Dependencies (load in order) |
| -------------------- | ---------------------------------------- |
| Core module | [cldr.js][] |
| Currency module | globalize.js (core), globalize/number.js, and globalize/plural.js (only required for "code" or "name" styles) |
| Date module | globalize.js (core) and globalize/number.js |
| Message module | globalize.js (core) and globalize/plural.js (if using messages that need pluralization support) |
| Number module | globalize.js (core) |
| Plural | globalize.js (core) |
| Relative time module | globalize.js (core), globalize/number.js, and globalize/plural.js |
| Unit module | globalize.js (core), globalize/number.js, and globalize/plural.js |
As an alternative to deducing this yourself, use this [online tool](http://johnnyreilly.github.io/globalize-so-what-cha-want/). The tool allows you to select the modules you're interested in using and tells you the Globalize files *and* CLDR JSON that you need.
[cldr.js]: https://github.com/rxaviers/cldrjs
#### 2. CLDR content
Globalize is the i18n software (the engine). Unicode CLDR is the i18n content (the fuel). You need to feed Globalize on the appropriate portions of CLDR prior to using it.
*(a) How do I figure out which CLDR portions are appropriate for my needs?*
Each Globalize function requires a special set of CLDR portions. Once you know which Globalize functionalities you need, you can deduce its respective CLDR requirements. See table below.
| Module | Required CLDR JSON files |
| -------------------- | ---------------------------------------- |
| Core module | cldr/supplemental/likelySubtags.json |
| Currency module | cldr/main/`locale`/currencies.json<br>cldr/supplemental/currencyData.json<br>+CLDR JSON files from number module<br>+CLDR JSON files from plural module for name style support |
| Date module | cldr/main/`locale`/ca-gregorian.json<br>cldr/main/`locale`/timeZoneNames.json<br>cldr/supplemental/metaZones.json<br>cldr/supplemental/timeData.json<br>cldr/supplemental/weekData.json<br>+CLDR JSON files from number module |
| Number module | cldr/main/`locale`/numbers.json<br>cldr/supplemental/numberingSystems.json |
| Plural module | cldr/supplemental/plurals.json (for cardinals)<br>cldr/supplemental/ordinals.json (for ordinals) |
| Relative time module | cldr/main/`locale`/dateFields.json<br>+CLDR JSON files from number and plural modules |
| Unit module | cldr/main/`locale`/units.json<br>+CLDR JSON files from number and plural module |
As an alternative to deducing this yourself, use this [online tool](http://johnnyreilly.github.io/globalize-so-what-cha-want/). The tool allows you to select the modules you're interested in using and tells you the Globalize files *and* CLDR JSON that you need.
*(b) How am I supposed to get and load CLDR content?*
Learn [how to get and load CLDR content...](doc/cldr.md) and use
[`Globalize.load()`](#core-module) to load it.
#### 3. IANA time zone data
The IANA time zone (tz) database, sometimes called the Olson database, is the standard data used by Unicode CLDR, ECMA-402, Linux, UNIX, Java, ICU, and others. It's used by Globalize to circumvent the JavaScript limitations with respect to manipulating date in time zones other than the user's environment.
In short, feed Globalize on IANA time zone data if you need to format or parse dates in a specific time zone, independently of the user's environment, e.g., `America/Los_Angeles`.
It's important to note there's no official IANA time zone data in the JSON format. Therefore, [`iana-tz-data`](https://github.com/rxaviers/iana-tz-data) has been adopted for convenience.
Learn more on [`Globalize.loadTimeZone()`](#date-module).
### Usage
Globalize's consumable-files are located in the `./dist` directory. If you don't find it, it's because you are using a development branch. You should either use a tagged version or [build the distribution files yourself](#build). Read [installation](#installation) above if you need more information on how to download.
Globalize can be used for a variety of different i18n tasks, eg. formatting or parsing dates, formatting or parsing numbers, formatting messages, etc. You may NOT need Globalize in its entirety. For that reason, we made it modular. So, you can cherry-pick the pieces you need, eg. load `dist/globalize.js` to get Globalize core, load `dist/globalize/date.js` to extend Globalize with Date functionalities, etc.
An example is worth a thousand words. Check out our [Examples](#examples) section below.
### Performance
When formatting or parsing, there's actually a two-step process: (a) the formatter (or parser) *creation* and (b) its *execution*, where creation takes an order of magnitude more time (more expensive) than execution. In the creation phase, Globalize traverses the CLDR tree, processes data (e.g., expands date patterns, parses plural rules, etc), and returns a function that actually executes the formatting or parsing.
```js
// Formatter creation.
var formatter = Globalize.numberFormatter();
// Formatter execution (roughly 10x faster than above).
formatter( Math.PI );
// > 3.141
```
As a rule of thumb for optimal performance, cache your formatters and parsers. For example: (a) on iterations, generate them outside the loop and reuse while looping; (b) on server applications, generate them in advance and execute when requests arrive.
### Compilation and the Runtime modules
Take advantage of compiling your formatters and/or parsers during build time when deploying to production. It's much faster than generating them in real-time and it's also much smaller (i.e., better loading performance).
Your compiled formatters and parsers allow you to skip a big part of the library and also allow you to skip loading CLDR data, because they have already been created (see [Performance](#performance) above for more information).
To illustrate, see our [Basic Globalize Compiler example][].
#### Globalize Compiler
For information about the Globalize Compiler CLI or its JavaScript API, see the [Globalize Compiler documentation][].
[Globalize Compiler documentation]: https://github.com/globalizejs/globalize-compiler#README
### Examples
The fastest and easiest way to use Globalize is by integrating it into your existing tools.
- [Application example using webpack and npm](examples/app-npm-webpack/): easy to get started, automated CLDR loading and precompilation for production, but requires npm and webpack knowledge.
- [Application example using globalize-express middleware with any express web app](https://github.com/devangnegandhi/globalize-express/tree/master/example): easy to incorporate globalize as a middleware within your Express web app. (also checkout [globalize-express](https://github.com/devangnegandhi/globalize))
If you're using a different tool than the one above, but you're comfortable using JavaScript modules (such as ES6 modules, CommonJS, or AMD) and package managers like npm or bower, you may want to check out the following examples. Note you'll need to compile your code for production yourself.
- [Basic example using AMD and bower](examples/amd-bower/): feeding Globalize on CLDR is not completely transparent.
- [Basic example using Node.js and npm](examples/node-npm/): feeding Globalize on CLDR is not completely transparent.
- [Basic Globalize Compiler example][]: shows how to use Globalize Compiler CLI.
[Basic Globalize Compiler example]: examples/globalize-compiler/
If you're using none of the tools above, but instead you're using the plain and old script tags only, the following example may interest you. Note Globalize allows you to go low level like this. But, acknowledge that you'll need to handle dependencies and CLDR loading manually yourself.
- [Basic example using plain JavaScript](examples/plain-javascript/): requires loading CLDR and handling dependencies manually.
### Community
You can find us on [Slack](https://globalizejs.slack.com/). If you're new, [join here](https://join.slack.com/t/globalizejs/shared_invite/zt-3tc3js1e-ETn09rNHL_5fclun8jtckQ).
## API
### Core module
#### `Globalize.load( cldrJSONData, ... )`
This method allows you to load CLDR JSON locale data. `Globalize.load()` is a proxy to `Cldr.load()`. [Read more...](doc/api/core/load.md)
#### `Globalize.locale( [locale|cldr] )`
Set default locale, or get it if locale argument is omitted. [Read more...](doc/api/core/locale.md)
#### `[new] Globalize( locale|cldr )`
Create a Globalize instance. [Read more...](doc/api/core/constructor.md)
#### Locales
A locale is an identifier (id) that refers to a set of user preferences that tend to be shared across significant swaths of the world. In technical terms, it's a String composed of three parts: language, script, and region. For example:
| locale | description |
| ------------ | ---------------------------------------- |
| *en-Latn-US* | English as spoken in the Unites States in the Latin script. |
| *en-US* | English as spoken in the Unites States (Latin script is deduced given it's the most likely script used in this place). |
| *en* | English (United States region and Latin script are deduced given they are respectively the most likely region and script used in this place). |
| *en-GB* | English as spoken in the United Kingdom (Latin script is deduced given it's the most likely script used in this place). |
| *en-IN* | English as spoken in India (Latin script is deduced). |
| *es* | Spanish (Spain region and Latin script are deduced). |
| *es-MX* | Spanish as spoken in Mexico (Latin script is deduced). |
| *zh* | Chinese (China region and Simplified Han script are deduced). |
| *zh-TW* | Chinese as spoken in Taiwan (Traditional Han script is deduced). |
| *ja* | Japanese (Japan region and Japanese script are deduced). |
| *de* | German (Germany region and Latin script are deduced). |
| *pt* | Portuguese (Brazil region and Latin script are deduced). |
| *pt-PT* | Portuguese as spoken in Portugal (Latin script is deduced). |
| *fr* | French (France region and Latin script are deduced). |
| *ru* | Russian (Russia region and Cyrillic script are deduced). |
| *ar* | Arabic (Egypt region and Arabic script are deduced). |
The likely deductibility is computed by using CLDR data, which is based on the population and the suppress-script data in BCP47 (among others). The data is heuristically derived, and may change over time.
Figure out the deduced information by looking at the `cldr.attributes.maxLanguageId` property of a Globalize instance:
```js
var Globalize = require( "globalize" );
Globalize.load( require( "cldr-data" ).entireSupplemental() );
Globalize( "en" ).cldr.attributes.maxLanguageId;
// > "en-Latn-US"
```
Globalize supports all the locales available in CLDR, which are around 740. For more information, search for coverage charts at the downloads section of http://cldr.unicode.org/.
Read more details about locale at [UTS#35 locale][].
[UTS#35 locale]: http://www.unicode.org/reports/tr35/#Locale
### Date module
#### `Globalize.loadTimeZone( ianaTzData )`
This method allows you to load IANA time zone data to enable `options.timeZone` feature on date formatters and parsers.
[Read more...](doc/api/date/load-iana-time-zone.md)
#### `.dateFormatter( [options] )`
Return a function that formats a date according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
```javascript
.dateFormatter()( new Date() )
// > "11/30/2010"
.dateFormatter({ skeleton: "GyMMMd" })( new Date() )
// > "Nov 30, 2010 AD"
.dateFormatter({ date: "medium" })( new Date() )
// > "Nov 1, 2010"
.dateFormatter({ time: "medium" })( new Date() )
// > "5:55:00 PM"
.dateFormatter({ datetime: "medium" })( new Date() )
// > "Nov 1, 2010, 5:55:00 PM"
.dateFormatter({ datetime: "full", timeZone: "America/New_York" })( new Date() );
// > "Monday, November 1, 2010 at 3:55:00 AM Eastern Daylight Time"
.dateFormatter({ datetime: "full", timeZone: "America/Los_Angeles" })( new Date() );
// > "Monday, November 1, 2010 at 12:55:00 AM Pacific Daylight Time"
```
[Read more...](doc/api/date/date-formatter.md)
#### `.dateToPartsFormatter( [options] )`
Return a function that formats a date into parts tokens according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
```javascript
.dateToPartsFormatter()( new Date() )
// > [
// { "type": "month", "value": "3" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "17" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2017" }
// ]
```
[Read more...](doc/api/date/date-to-parts-formatter.md)
#### `.dateParser( [options] )`
Return a function that parses a string representing a date into a JavaScript Date object according to the given `options`. The default parsing assumes numeric year, month, and day (i.e., `{ skeleton: "yMd" }`).
```javascript
.dateParser()( "11/30/2010" )
// > new Date( 2010, 10, 30, 0, 0, 0 )
.dateParser({ skeleton: "GyMMMd" })( "Nov 30, 2010 AD" )
// > new Date( 2010, 10, 30, 0, 0, 0 )
.dateParser({ date: "medium" })( "Nov 1, 2010" )
// > new Date( 2010, 10, 30, 0, 0, 0 )
.dateParser({ time: "medium" })( "5:55:00 PM" )
// > new Date( 2015, 3, 22, 17, 55, 0 ) // i.e., today @ 5:55PM
.dateParser({ datetime: "medium" })( "Nov 1, 2010, 5:55:00 PM" )
// > new Date( 2010, 10, 30, 17, 55, 0 )
```
[Read more...](doc/api/date/date-parser.md)
#### `.formatDate( value [, options] )`
Alias for `.dateFormatter( [options] )( value )`.
#### `.formatDateToParts( value [, options] )`
Alias for `.dateToPartsFormatter( [options] )( value )`.
#### `.parseDate( value [, options] )`
Alias for `.dateParser( [options] )( value )`.
### Message module
#### `Globalize.loadMessages( json )`
Load messages data. [Read more...](doc/api/message/load-messages.md)
#### `.messageFormatter( path ) ➡ function( [variables] )`
Return a function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections.
```javascript
.messageFormatter( "task" )( 1000 )
// > "You have 1,000 tasks remaining"
.messageFormatter( "like" )( 3 )
// > "You and 2 others liked this"
```
[Read more...](doc/api/message/message-formatter.md)
#### `.formatMessage( path [, variables ] )`
Alias for `.messageFormatter( path )([ variables ])`.
### Number module
#### `.numberFormatter( [options] )`
Return a function that formats a number according to the given options or locale's defaults.
```javascript
.numberFormatter()( pi )
// > "3.142"
.numberFormatter({ maximumFractionDigits: 5 })( pi )
// > "3.14159"
.numberFormatter({ round: "floor" })( pi )
// > "3.141"
.numberFormatter({ minimumFractionDigits: 2 })( 10000 )
// > "10,000.00"
.numberFormatter({ style: "percent" })( 0.5 )
// > "50%"
.numberFormatter({ compact: "short", maximumFractionDigits: 0 })( 14305 )
// > "14K"
```
[Read more...](doc/api/number/number-formatter.md)
#### `.numberToPartsFormatter( [options] )`
Return a function that formats a number into parts tokens according to the given options or locale's defaults.
```javascript
.numberToPartsFormatter()( new Date() )
// > [
// { "type": "integer", "value": "3" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "142" }
// ]
```
[Read more...](doc/api/number/number-to-parts-formatter.md)
#### `.numberParser( [options] )`
Return a function that parses a string representing a number according to the given options or locale's defaults.
```javascript
.numberParser()( "3.14159" )
// > 3.14159
.numberParser()( "10,000.00" )
// > 10000
.numberParser({ style: "percent" })( "50%" )
// > 0.5
```
[Read more...](doc/api/number/number-parser.md)
#### `.formatNumber( value [, options] )`
Alias for `.numberFormatter( [options] )( value )`.
#### `.formatNumberToParts( value [, options] )`
Alias for `.numberToPartsFormatter( [options] )( value )`.
#### `.parseNumber( value [, options] )`
Alias for `.numberParser( [options] )( value )`.
### Currency module
#### `.currencyFormatter( currency [, options] )`
Return a function that formats a currency according to the given options or locale's defaults.
```javascript
.currencyFormatter( "USD" )( 1 )
// > "$1.00"
.currencyFormatter( "USD", { style: "accounting" })( -1 )
// > "($1.00)"
.currencyFormatter( "USD", { style: "name" })( 69900 )
// > "69,900.00 US dollars"
.currencyFormatter( "USD", { style: "code" })( 69900 )
// > "69,900.00 USD"
.currencyFormatter( "USD", { round: "ceil" })( 1.491 )
// > "$1.50"
```
[Read more...](doc/api/currency/currency-formatter.md)
#### `.currencyToPartsFormatter( currency [, options] )`
Return a function that formats a currency into parts tokens according to the given options or locale's defaults.
```javascript
.currencyToPartsFormatter()( new Date() )
// > [
// { "type": "currency", "value": "USD" },
// { "type": "literal", "value": " " },
// { "type": "integer", "value": "69" },
// { "type": "group", "value": "," },
// { "type": "integer", "value": "900" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "00" }
// ]
```
[Read more...](doc/api/currency/currency-to-parts-formatter.md)
#### `.formatCurrency( value, currency [, options] )`
Alias for `.currencyFormatter( currency [, options] )( value )`.
#### `.formatCurrencyToParts( value, currency [, options] )`
Alias for `.currencyToPartsFormatter( currency [, options] )( value )`.
### Plural module
#### `.pluralGenerator( [options] )`
Return a function that returns the value's corresponding plural group: `zero`, `one`, `two`, `few`, `many`, or `other`.
The function may be used for cardinals or ordinals.
```javascript
.pluralGenerator()( 0 )
// > "other"
.pluralGenerator()( 1 )
// > "one"
.pluralGenerator({ type: "ordinal" })( 1 )
// > "one"
.pluralGenerator({ type: "ordinal" })( 2 )
// > "two"
```
[Read more...](doc/api/plural/plural-generator.md)
#### `.plural( value[, options ] )`
Alias for `.pluralGenerator( [options] )( value )`.
### Relative time module
#### `.relativeTimeFormatter( unit [, options] )`
Returns a function that formats a relative time according to the given unit, options, and the default/instance locale.
```javascript
.relativeTimeFormatter( "day" )( 1 )
// > "tomorrow"
.relativeTimeFormatter( "month" )( -1 )
// > "last month"
.relativeTimeFormatter( "month" )( 3 )
// > "in 3 months"
```
[Read more...](doc/api/relative-time/relative-time-formatter.md)
#### `.formatRelativeTime( value, unit [, options] )`
Alias for `.relativeTimeFormatter( unit, options )( value )`.
### Unit module
#### `.unitFormatter( unit [, options] )`
Returns a function that formats a unit according to the given unit, options, and the default/instance locale.
```javascript
.unitFormatter( "second" )( 10 )
// > "10 seconds"
.unitFormatter( "second", { form: "short" } )( 10 )
// > "10 secs"
.unitFormatter( "second", { form: "narrow" } )( 10 )
// > "10s"
```
[Read more...](doc/api/unit/unit-formatter.md)
#### `.formatUnit( value, unit [, options] )`
Alias for `.unitFormatter( unit, options )( value )`.
## Error reference
### CLDR Errors
- **`E_INVALID_CLDR`**
Thrown when a CLDR item has an invalid or unexpected value.
[Read more...](doc/error/e-invalid-cldr.md)
- **`E_MISSING_CLDR`**
Thrown when any required CLDR item is NOT found.
[Read more...](doc/error/e-missing-cldr.md)
### Parameter Errors
- **`E_INVALID_PAR_TYPE`**
Thrown when a parameter has an invalid type on any static or instance methods.
[Read more...](doc/error/e-invalid-par-type.md)
- **`E_INVALID_PAR_VALUE`**
Thrown for certain parameters when the type is correct, but the value is
invalid.
[Read more...](doc/error/e-invalid-par-value.md)
- **`E_MISSING_PARAMETER`**
Thrown when a required parameter is missing on any static or instance methods.
[Read more...](doc/error/e-missing-parameter.md)
- **`E_PAR_OUT_OF_RANGE`**
Thrown when a parameter is not within a valid range of values.
[Read more...](doc/error/e-par-out-of-range.md)
### Other Errors
- **`E_DEFAULT_LOCALE_NOT_DEFINED`**
Thrown when any static method, eg. `Globalize.formatNumber()` is used prior to setting the Global locale with `Globalize.locale( <locale> )`.
[Read more...](doc/error/e-default-locale-not-defined.md)
- **`E_MISSING_PLURAL_MODULE`**
Thrown when plural module is needed, but not loaded, eg. to format currencies using the named form.
[Read more...](doc/error/e-missing-plural-module.md)
- **`E_UNSUPPORTED`**
Thrown for unsupported features, eg. to format unsupported date patterns.
[Read more...](doc/error/e-unsupported.md)
## Contributing
If you are having trouble using Globalize after reading the documentation carefully, please post a question to [StackOverflow with the "javascript-globalize" tag][]. Questions that include a minimal demo are more likely to receive responses.
In the spirit of open source software development, we always encourage community code contribution. To help you get started and before you jump into writing code, be sure to read [CONTRIBUTING.md](CONTRIBUTING.md).
[StackOverflow with the "javascript-globalize" tag]: http://stackoverflow.com/tags/javascript-globalize
For ideas where to start contributing, see the following queries to find what best suites your interest: [quick change][], [new features][], [bug fixes][], [documentation improvements][], [date module][], [currency module][], [message module][], [number module][], [plural module][], [relative time module][]. Last but not least, feel free to [get in touch](http://irc.jquery.org/).
[bug fixes]: https://github.com/globalizejs/globalize/labels/bug
[documentation improvements]: https://github.com/globalizejs/globalize/labels/docs
[new features]: https://github.com/globalizejs/globalize/labels/new%20feature
[quick change]: https://github.com/globalizejs/globalize/labels/quick%20change
[currency module]: https://github.com/globalizejs/globalize/labels/currency%20module
[date module]: https://github.com/globalizejs/globalize/labels/date%20module
[message module]: https://github.com/globalizejs/globalize/labels/message%20module
[number module]: https://github.com/globalizejs/globalize/labels/number%20module
[plural module]: https://github.com/globalizejs/globalize/labels/plural%20module
[relative time module]: https://github.com/globalizejs/globalize/labels/relative%20time%20module
### Roadmap
Our roadmap is the collection of all open issues and pull requests where you can find:
- [Ongoing work][] lists our current sprint. Here you find where we're actively working on at this very moment. Priority is determined by the community needs and volunteering. If there is anything you want to be done, share your thoughts with us on any existing or new issue and especially volunteer to do it.
- [Everything else][] is potential next work that you could help us to accomplish now. Releases are published following semver rules as often as possible.
[Ongoing work]: https://github.com/globalizejs/globalize/labels/Current%20Sprint
[Everything else]: https://github.com/globalizejs/globalize/issues?utf8=%E2%9C%93&amp;q=is%3Aopen+-label%3A%22Current+Sprint%22+
## Development
### File structure
```
├── bower.json (metadata file)
├── CONTRIBUTING.md (doc file)
├── dist/ (consumable files, the built files)
├── external/ (external dependencies, eg. cldr.js, QUnit, RequireJS)
├── Gruntfile.js (Grunt tasks)
├── LICENSE (license file)
├── package.json (metadata file)
├── README.md (doc file)
├── src/ (source code)
│ ├── build/ (build helpers, eg. intro, and outro)
│ ├── common/ (common function helpers across modules)
│ ├── core.js (core module)
│ ├── date/ (date source code)
│ ├── date.js (date module)
│ ├── message.js (message module)
│ ├── number.js (number module)
│ ├── number/ (number source code)
│ ├── plural.js (plural module)
│ ├── plural/ (plural source code)
│ ├── relative-time.js (relative time module)
│ ├── relative-time/ (relative time source code)
│ ├── unit.js (unit module)
│ ├── unit/ (unit source code)
│ └── util/ (basic JavaScript helpers polyfills, eg array.map)
└── test/ (unit and functional test files)
├── fixtures/ (CLDR fixture data)
├── functional/ (functional tests)
├── functional.html
├── functional.js
├── unit/ (unit tests)
├── unit.html
└── unit.js
```
### Source files
The source files are as granular as possible. When combined to generate the build file, all the excessive/overhead wrappers are cut off. It's following the same build model of jQuery and Modernizr.
Core, and all modules' public APIs are located in the `src/` directory, ie. `core.js`, `date.js`, `message.js`, `number.js`, and `plural.js`.
### Install development external dependencies
Install Grunt and external dependencies. First, install the [grunt-cli](http://gruntjs.com/getting-started#installing-the-cli) and [bower](http://bower.io/) packages if you haven't before. These should be installed globally (like this: `npm install -g grunt-cli bower`). Then:
```bash
npm install && bower install
```
### Tests
Tests can be run either in the browser or using Node.js (via Grunt) after having installed the external development dependencies (for more details, see above).
#### Unit tests
To run the unit tests, run `grunt test:unit`, or run `grunt connect:keepalive` and open `http://localhost:9001/test/unit.html` in a browser. It tests the very specific functionality of each function (sometimes internal/private).
The goal of the unit tests is to make it easy to spot bugs, easy to debug.
#### Functional tests
To run the functional tests, create the dist files by running `grunt`. Then, run `grunt test:functional`, or open `http://localhost:9001/test/functional.html` in a browser. Note that `grunt` will automatically run unit and functional tests for you to ensure the built files are safe.
The goal of the functional tests is to ensure that everything works as expected when it is combined.
### Build
Build the distribution files after having installed the external development dependencies (for more details, see above).
```bash
grunt
```

View File

@@ -1,22 +0,0 @@
{
"name": "globalize",
"license": "MIT",
"ignore": [
"**/.*",
"test",
"CONTRIBUTING.md",
"bower.json"
],
"dependencies": {
"cldrjs": "^0.5.4"
},
"devDependencies": {
"cldr-data": ">=25",
"es5-shim": "3.4.0",
"make-plural": "eemeli/make-plural.js#3.0.0",
"messageformat": "SlexAxton/messageformat.js#v0.3.0-1",
"requirejs": "2.1.20",
"requirejs-plugins": "1.0.2",
"requirejs-text": "2.0.10"
}
}

View File

@@ -1,17 +0,0 @@
{
"test_framework": "qunit",
"test_path": [ "test/unit.html", "test/functional.html" ],
"browsers": [
"chrome_previous",
"chrome_latest",
"firefox_previous",
"firefox_latest",
"ie_9",
"ie_10",
"ie_11",
"opera_previous",
"opera_latest",
"safari_previous",
"safari_latest"
]
}

View File

@@ -1,28 +0,0 @@
## [new] Globalize( locale|cldr )
Create a Globalize instance.
### Parameters
#### locale|cldr
Locale string or [Cldr instance](https://github.com/rxaviers/cldrjs) of the instance.
### Example
Prior to creating any Globalize instance, you must load `cldr/supplemental/likelySubtags.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
var en = new Globalize( "en" );
// You can optionally omit the `new` operator.
var pt = Globalize( "pt" );
en.formatNumber( 3.1415 );
// > 3.142
pt.formatNumber( 3.1415 );
// > 3,142
```

View File

@@ -1,96 +0,0 @@
## Globalize.load( cldrJSONData, ... )
This method allows you to load CLDR JSON locale data. `Globalize.load()` is a proxy to `Cldr.load()`.
This method can be called as many times as needed. All passed JSON objects are deeply merged internally.
For more information, see https://github.com/rxaviers/cldrjs#readme.
### Parameters
#### cldrJSONData
A JSON object with CLDR data. See [Getting Started](#../../../README.md#2-cldr-content) for more information.
### Example
```javascript
Globalize.load({
"main": {
"en": {
"identity": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"generation": {
"_date": "$Date: 2014-03-13 22:27:12 -0500 (Thu, 13 Mar 2014) $"
},
"language": "en"
},
"dates": {
"calendars": {
"gregorian": {
"months": {
"format": {
"abbreviated": {
"1": "Jan",
"2": "Feb",
"3": "Mar",
"4": "Apr",
"5": "May",
"6": "Jun",
"7": "Jul",
"8": "Aug",
"9": "Sep",
"10": "Oct",
"11": "Nov",
"12": "Dec"
}
}
},
"dayPeriods": {
"format": {
"wide": {
"am": "AM",
"am-alt-variant": "am",
"noon": "noon",
"pm": "PM",
"pm-alt-variant": "pm"
}
}
},
"dateFormats": {
"medium": "MMM d, y"
},
"timeFormats": {
"medium": "h:mm:ss a",
},
"dateTimeFormats": {
"medium": "{1}, {0}"
}
}
}
},
"numbers": {
"defaultNumberingSystem": "latn",
"symbols-numberSystem-latn": {
"group": ","
},
"decimalFormats-numberSystem-latn": {
"standard": "#,##0.###"
}
}
}
},
"supplemental": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"likelySubtags": {
"en": "en-Latn-US",
}
}
});
```

View File

@@ -1,43 +0,0 @@
## Globalize.locale( [locale|cldr] )
Set default locale, or get it if locale argument is omitted.
Return the default [Cldr instance](https://github.com/rxaviers/cldrjs).
An application that supports globalization and/or localization will need to have a way to determine the user's preference. Attempting to automatically determine the appropriate locale is useful, but it is good practice to always offer the user a choice, by whatever means.
Whatever your mechanism, it is likely that you will have to correlate the user's preferences with the list of locale data supported in the app. This method allows you to select the best match given the locale data that you have included and to set the Globalize locale to the one which the user prefers.
LanguageMatching TBD (CLDR's spec http://www.unicode.org/reports/tr35/#LanguageMatching).
### Parameters
#### locale|cldr
- The locale string, e.g., `"en"`, `"pt-BR"`, or `"zh-Hant-TW"`. Or,
- The [Cldr instance](https://github.com/rxaviers/cldrjs), e.g., new `Cldr( "en" )`.
### Example
Prior to using this function, you must load `cldr/supplemental/likelySubtags.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
// Set "pt" as our default locale.
Globalize.locale( "pt" );
// Get default locale.
Globalize.locale();
// > {
// attributes: {
// "languageId": "pt",
// "maxLanguageId": "pt_Latn_BR",
// "language": "pt",
// "script": "Latn",
// "territory": "BR",
// "region": "BR"
// },
// some more stuff...
// }
```

View File

@@ -1,196 +0,0 @@
## .currencyFormatter( currency [, options] ) ➜ function( value )
Return a function that formats a `currency` according to the given `options` or locale's defaults.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### currency
3-letter currency code as defined by ISO 4217, eg. `"USD"`.
#### options.style
Optional. String `"symbol"` (default), `"accounting"`, `"code"` or `"name"`. See [`.numberFormatter( [options] )`](../number/number-formatter.md) for more options.
#### value
Number to be formatted, eg. `9.99`.
### Example
#### Static Formatter
Prior to using any currency methods, you must load `cldr/main/{locale}/currencies.json`, `cldr/supplemental/currencyData.json`, and the CLDR content required by the number module. If using plural messages, you also must load the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Using the default options
You can use the static method `Globalize.currencyFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyFormatter( "USD" );
formatter( 9.99 );
// > "$9.99"
```
#### Instance Formatter
You can use the instance method `.currencyFormatter()`, which uses the instance locale.
```javascript
var deFormatter = Globalize( "de" ).currencyFormatter( "EUR" ),
zhFormatter = Globalize( "zh" ).currencyFormatter( "EUR" );
deFormatter( 9.99 );
// > "9,99 €"
zhFormatter( 9.99 );
// > "€ 9.99"
```
For comparison, follow the formatting output of different symbols in different locales.
| 3-letter currency code | en (English) | de (German) | zh (Chinese) |
| ---------------------------------- | ------------ | ----------- | ------------ |
| `.currencyFormatter( "USD" )( 1 )` | `$1.00` | `1,00 $` | `US$ 1.00` |
| `.currencyFormatter( "EUR" )( 1 )` | `€1.00` | `1,00 €` | `€ 1.00` |
| `.currencyFormatter( "CNY" )( 1 )` | `CN¥1.00` | `1,00 CN¥` | `¥ 1.00` |
| `.currencyFormatter( "JPY" )( 1 )` | `¥1` | `1 ¥` | `JP¥ 1` |
| `.currencyFormatter( "GBP" )( 1 )` | `£1.00` | `1,00 £` |  1.00` |
| `.currencyFormatter( "BRL" )( 1 )` | `R$1.00` | `1,00 R$` | `R$ 1.00` |
#### Using alternative `options.symbolForm`
Using the narrow symbol form, the same symbols may be used for multiple currencies. Thus the symbol may be ambiguous, and should only be used where the context is clear.
```js
Globalize( "en" ).currencyFormatter( "HKD" )( 1 );
// > "HK$1.00"
Globalize( "en" ).currencyFormatter( "HKD", { symbolForm: "narrow" } )( 1 );
// > "$1.00"
```
#### Configuring style
For the accounting variation of the symbol format, use `style: "accounting"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "accounting"
});
formatter( -1 );
// > "($1.00)"
```
For plural messages, use `style: "name"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "name"
});
formatter( 0 );
// > "0.00 US dollars"
formatter( 1 );
// > "1.00 US dollar"
```
For comparison, follow the formatting output of different symbols in different locales using the plural messages `Globalize( locale ).currencyFormatter( currency, { style: "name" } )( 1 )`.
| 3-letter currency code | en (English) | de (German) | zh (Chinese) |
| ---------------------- | ----------------------------- | -------------------------------- | ------------ |
| `USD` | `1.00 US dollar` | `1,00 US-Dollar` | `1.00美元` |
| `EUR` | `1.00 euro` | `1,00 Euro` | `1.00欧元` |
| `CNY` | `1.00 Chinese yuan` | `1,00 Chinesischer Yuan` | `1.00人民币` |
| `JPY` | `1 Japanese yen` | `1 Japanischer Yen` | `1日元` |
| `GBP` | `1.00 British pound sterling` | `1,00 Britisches Pfund Sterling` | `1.00英镑` |
| `BRL` | `1.00 Brazilian real` | `1,00 Brasilianischer Real` | `1.00巴西雷亚尔` |
For the international currency code, use `style: "code"`.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD", {
style: "code"
});
formatter( 9.99 );
// > "9.99 USD"
```
#### Configuring inherited number options
Override the number of digits, grouping separators, rounding function or any other [`.numberFormatter()` options](../number/number-formatter.md).
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyFormatter( "USD", {
minimumFractionDigits: 0,
style: "name"
});
formatter( 1 );
// > "1 US dollar"
formatter = Globalize.currencyFormatter( "USD", {
round: "ceil"
});
formatter( 1.491 );
// > "$1.50"
```
#### Formatting Compact Currencies
```js
var shortFormatter = Globalize( "en" ).currencyFormatter( "USD", {
compact: "short"
});
var longFormatter = Globalize( "en" ).currencyFormatter( "USD", {
compact: "long"
});
shortFormatter( 12830000000 );
// > "$13B"
longFormatter( 12830000000 );
// > "$13 billion"
```
The minimumSignificantDigits and maximumSignificantDigits options are specially useful to control the number of digits to display.
```js
Globalize( "en" ).formatCurrency( 12830000000, "USD", {
compact: "short",
minimumSignificantDigits: 3,
maximumSignificantDigits: 3
});
// > "$12.8B"
```
#### Performance Suggestion
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
var formatter = Globalize( "en" ).currencyFormatter( "USD" );
renderInvoice({
prices: prices.map(function( price ) {
return formatter( price );
})
});
```

View File

@@ -1,117 +0,0 @@
## .currencyToPartsFormatter( currency [, options] ) ➜ function( value )
Return a function that formats a `currency` into parts tokens according to the given `options` or locale's defaults.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### currency
3-letter currency code as defined by ISO 4217, eg. `"USD"`.
#### options
Please, see [.currencyFormatter() options](./currency-formatter.md#parameters).
#### value
Number to be formatted, eg. `9.99`.
### Returns
An Array of objects containing the formatted currency in parts. The returned structure looks like this:
```js
[
{ type: "day", value: "17" },
{ type: "weekday", value: "Monday" }
]
```
Possible types are the following:
- `currency`
The currency string, such as the symbols `"$"` and `"€"` or the name `"Dollar"`, `"Euro"` depending on which style is used.
Please, see [.numberToPartsFormatter()](../number/number-to-parts-formatter.md#returns) for details about the inherited number parts such as `decimal`, `fraction`, `group`, `infinity`, `integer`, `literal`, `minusSign`, `nan`, `plusSign`, `percentSign`, and `compact`.
### Example
Prior to using any currency methods, you must load `cldr/main/{locale}/currencies.json`, `cldr/supplemental/currencyData.json`, and the CLDR content required by the number module. If using plural messages, you also must load the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Static Formatter
#### Using the default options
You can use the static method `Globalize.currencyToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.currencyToPartsFormatter( "USD" );
formatter( 9.99 );
// > [
// { "type": "currency", "value": "$" },
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "99" }
// ]
```
#### Instance Formatter
You can use the instance method `.currencyFormatter()`, which uses the instance locale.
```javascript
var deFormatter = Globalize( "de" ).currencyToPartsFormatter( "EUR" ),
zhFormatter = Globalize( "zh" ).currencyToPartsFormatter( "EUR" );
deFormatter( 9.99 );
// > [
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "," },
// { "type": "fraction", "value": "99" },
// { "type": "literal", "value": " " },
// { "type": "currency", "value": "€" }
// ]
zhFormatter( 9.99 );
// > [
// { "type": "currency", "value": "€" },
// { "type": "integer", "value": "9" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "99" }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
#### More Examples
Please, see [.currencyFormatter() example](./currency-formatter.md#example) for additional examples such as using alternative `symbolForm`, configuring `style` (symbol, accounting, and name styles), and the inherited number options (e.g., compact numbers).
#### Performance Suggestion
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
var formatter = Globalize( "en" ).currencyToPartsFormatter( "USD" );
renderInvoice({
prices: prices.map(function( price ) {
return formatter( price );
})
});
```

View File

@@ -1,203 +0,0 @@
## .dateFormatter( [options] ) ➜ function( value )
Return a function that formats a date according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
The returned function is invoked with one argument: the Date instance `value` to be formatted.
### Parameters
#### options.skeleton
String value indicating a skeleton (see description above), eg. `{ skeleton: "GyMMMd" }`.
Skeleton provides a more flexible formatting mechanism than the predefined list `full`, `long`, `medium`, or `short` represented by date, time, or datetime. Instead, they are an open-ended list of patterns containing only date field information, and in a canonical order. For a complete list of skeleton patterns [check the unicode CLDR documentation](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table).
For example:
| locale | `"GyMMMd"` skeleton |
| ------ | ------------------------- |
| *en* | `"Apr 9, 2014 AD"` |
| *zh* | `"公元2014年4月9日"` |
| *es* | `"9 abr. de 2014 d. C."` |
| *ar* | `"٩ أبريل، ٢٠١٤ م"` |
| *pt* | `"9 de abr de 2014 d.C."` |
#### options.date
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ date: "full" }`.
#### options.time
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ time: "full" }`.
#### options.datetime
One of the following String values: `full`, `long`, `medium`, or `short`, eg., `{ datetime: "full" }`.
#### options.raw
String value indicating a machine [raw pattern (anything in the "Sym." column)](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table) eg. `{ raw: "dd/mm" }`. Note this is NOT recommended for i18n in general. Use `skeleton` instead.
#### options.timeZone
String based on the time zone names of the [IANA time zone database](https://www.iana.org/time-zones), such as `"Asia/Shanghai"`, `"Asia/Kolkata"`, `"America/New_York"`.
#### value
Date instance to be formatted, eg. `new Date()`;
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/metaZones.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateFormatter();
formatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "11/30/2010"
```
You can use the instance method `.dateFormatter()`, which uses the instance locale.
```javascript
var enFormatter = Globalize( "en" ).dateFormatter(),
deFormatter = Globalize( "de" ).dateFormatter();
enFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "11/30/2010"
deFormatter( new Date( 2010, 10, 30, 17, 55 ) );
// > "30.11.2010"
```
#### Using short, medium, long, and full presets
Use convenient presets for `date`, `time`, or `datetime`. Their possible values are: `short`, `medium`, `long`, and `full`.
| `presetValue` | `Globalize( "en" ).dateFormatter( presetValue )( new Date( 2010, 10, 1, 17, 55 ) )` |
| ------------------------ | ---------------------------------------- |
| `{ date: "short" }` | `"11/1/10"` |
| `{ date: "medium" }` | `"Nov 1, 2010"` |
| `{ date: "long" }` | `"November 1, 2010"` |
| `{ date: "full" }` | `"Monday, November 1, 2010"` |
| `{ time: "short" }` | `"5:55 PM"` |
| `{ time: "medium" }` | `"5:55:00 PM"` |
| `{ time: "long" }` | `"5:55:00 PM PST"` |
| `{ time: "full" }` | `"5:55:00 PM Pacific Standard Time"` |
| `{ datetime: "short" }` | `"11/1/10, 5:55 PM"` |
| `{ datetime: "medium" }` | `"Nov 1, 2010, 5:55:00 PM"` |
| `{ datetime: "long" }` | `"November 1, 2010 at 5:55:00 PM PST"` |
| `{ datetime: "full" }` | `"Monday, November 1, 2010 at 5:55:00 PM Pacific Standard Time"` |
For comparison, follow the same formatter `{ datetime: "short" }` on different locales.
| locale | `Globalize( locale ).dateFormatter({ datetime: "short" })( new Date( 2010, 10, 1, 17, 55 ) )` |
| ---------------- | ---------------------------------------- |
| *en* | `"11/1/10, 5:55 PM"` |
| *en_GB* | `"01/11/2010 17:55"` |
| *zh* | `"10/11/1 下午5:55"` |
| *zh-u-nu-native* | `"一〇/一一/一 下午五:五五"` |
| *es* | `"1/11/10 17:55"` |
| *de* | `"01.11.10 17:55"` |
| *pt* | `"01/11/10 17:55"` |
| *ar* | `"١/١١/٢٠١٠ ٥،٥٥ م"` |
#### Using open-ended skeletons
Use open-ended skeletons for more flexibility (see its description [above](#parameters)). See some examples below.
| `skeleton` | `Globalize( "en" ).dateFormatter( skeleton )( new Date( 2010, 10, 1, 17, 55 ) )` |
| ---------------------------- | ---------------------------------------- |
| `{ skeleton: "E" }` | `"Tue"` |
| `{ skeleton: "EHm" }` | `"Tue 17:55"` |
| `{ skeleton: "EHms" }` | `"Tue 17:55:00"` |
| `{ skeleton: "Ed" }` | `"30 Tue"` |
| `{ skeleton: "Ehm" }` | `"Tue 5:55 PM"` |
| `{ skeleton: "Ehms" }` | `"Tue 5:55:00 PM"` |
| `{ skeleton: "Gy" }` | `"2010 AD"` |
| `{ skeleton: "GyMMM" }` | `"Nov 2010 AD"` |
| `{ skeleton: "GyMMMEd" }` | `"Tue, Nov 30, 2010 AD"` |
| `{ skeleton: "GyMMMd" }` | `"Nov 30, 2010 AD"` |
| `{ skeleton: "H" }` | `"17"` |
| `{ skeleton: "Hm" }` | `"17:55"` |
| `{ skeleton: "Hms" }` | `"17:55:00"` |
| `{ skeleton: "M" }` | `"11"` |
| `{ skeleton: "MEd" }` | `"Tue, 11/30"` |
| `{ skeleton: "MMM" }` | `"Nov"` |
| `{ skeleton: "MMMEd" }` | `"Tue, Nov 30"` |
| `{ skeleton: "MMMd" }` | `"Nov 30"` |
| `{ skeleton: "Md" }` | `"11/30"` |
| `{ skeleton: "d" }` | `"30"` |
| `{ skeleton: "h" }` | `"5 PM"` |
| `{ skeleton: "hm" }` | `"5:55 PM"` |
| `{ skeleton: "hms" }` | `"5:55:00 PM"` |
| `{ skeleton: "ms" }` | `"55:00"` |
| `{ skeleton: "y" }` | `"2010"` |
| `{ skeleton: "yM" }` | `"11/2010"` |
| `{ skeleton: "yMEd" }` | `"Tue, 11/30/2010"` |
| `{ skeleton: "yMMM" }` | `"Nov 2010"` |
| `{ skeleton: "yMMMEd" }` | `"Tue, Nov 30, 2010"` |
| `{ skeleton: "yMMMd" }` | `"Nov 30, 2010"` |
| `{ skeleton: "yMd" }` | `"11/30/2010"` |
| `{ skeleton: "yQQQ" }` | `"Q4 2010"` |
| `{ skeleton: "yQQQQ" }` | `"4th quarter 2010"` |
| `{ skeleton: "GyMMMEdhms" }` | `"Tue, Nov 30, 2010 AD, 5:55:00 PM"` |
| `{ skeleton: "Ehms" }` | `"Tue 5:55:00 PM"` |
| `{ skeleton: "yQQQHm" }` | `"Q4 2010, 17:55"` |
| `{ skeleton: "MMMEdhm" }` | `"Tue, Nov 30, 5:55 PM"` |
| `{ skeleton: "yMMMdhm" }` | `"Nov 30, 2010, 5:55 PM"` |
```javascript
var globalize = Globalize( "en" ),
date = new Date( 2010, 10, 30, 17, 55 ),
monthDayFormatter = globalize.dateFormatter({ skeleton: "MMMd" }),
hourMinuteSecondFormatter = globalize.dateFormatter({ skeleton: "Hms" });
monthDayFormatter( date );
// > "Nov 30"
hourMinuteSecondFormatter( date );
// > "17:55:00"
```
#### Using time zones
Using specific timeZones, i.e., using `options.timezone`. Note that prior to using it, you must load IANA time zone data.
```js
Globalize.loadTimeZone( require( "iana-tz-data" ) );
```
```js
Globalize.locale( "en" );
Globalize.dateFormatter({ datetime: "medium", timeZone: "America/Los_Angeles" })( new Date() );
// > "Nov 1, 2010, 12:55:00 PM"
Globalize.dateFormatter({ datetime: "medium", timeZone: "America/Sao_Paulo" })( new Date() )
// > "Nov 1, 2010, 5:55:00 PM"
Globalize.dateFormatter({ datetime: "full", timeZone: "Europe/Berlin" })( new Date() )
// > "Monday, November 1, 2010 at 8:55:00 PM Central European Standard Time"
```
#### Note on performance
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
// In an application, this array could have a few hundred entries
var dates = [ new Date( 2010, 10, 30, 17, 55 ), new Date( 2015, 3, 18, 4, 25 ) ];
var formatter = Globalize( "en" ).dateFormatter({ time: "short" });
var formattedDates = dates.map(function( date ) {
return formatter( date );
});
// > Array [ "5:55 PM", "4:25 AM" ]
```

View File

@@ -1,60 +0,0 @@
## .dateParser( [options] ) ➜ function( value )
Return a function that parses a string representing a date into a JavaScript Date object according to the given `options`. The default parsing assumes numeric year, month, and day (i.e., `{ skeleton: "yMd" }`).
The returned function is invoked with one argument: the String `value` to be parsed.
### Parameters
#### options
See [.dateFormatter() options](./date-formatter.md#parameters).
#### value
String with date to be parsed, eg. `"11/1/10, 5:55 PM"`.
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.dateParser()`, which uses the default locale.
```javascript
var parser;
Globalize.locale( "en" );
parser = Globalize.dateParser();
parser( "1/2/2013" );
// > Wed Jan 02 2013 00:00:00
Globalize.locale( "es" );
parser = Globalize.dateParser();
parser( "1/2/2013" );
// > Fri Feb 01 2013 00:00:00
```
You can use the instance method `.dateParser()`, which uses the instance locale.
```javascript
var esParser = Globalize( "es" ).dateParser({ date: short });
esParser( "1/2/13" );
// > Fri Feb 01 2013 00:00:00
```
For improved performance on iterations, first create the parser. Then, reuse it
on each loop.
```javascript
var formattedDates = [ new Date( a ), new Date( b ), ... ];
var parser = Globalize( "en" ).dateParser({ time: "short" });
dates = formattedDates.map(function( formattedDate ) {
return parser( formattedDate );
});
```

View File

@@ -1,176 +0,0 @@
## .dateToPartsFormatter( [options] ) ➜ function( value )
Return a function that formats a date into parts tokens according to the given `options`. The default formatting is numeric year, month, and day (i.e., `{ skeleton: "yMd" }`.
The returned function is invoked with one argument: the Date instance `value` to be formatted.
### Parameters
#### options
Please, see [.dateFormatter() options](./date-formatter.md#parameters).
#### value
Date instance to be formatted, eg. `new Date()`;
### Returns
An Array of objects containing the formatted date in parts. The returned structure looks like this:
```js
[
{ type: "day", value: "17" },
{ type: "weekday", value: "Monday" }
]
```
Possible types are the following:
- `day`
The string used for the day, e.g., `"17"`, `"١٦"`.
- `dayperiod`
The string used for the day period, e.g., `"AM"`, `"PM"`.
- `era`
The string used for the era, e.g., `"AD"`, `"d. C."`.
- `hour`
The string used for the hour, e.g., `"3"`, `"03"`.
- `literal`
The string used for separating date and time values, e.g., `"/"`, `", "`,
`"o'clock"`, `" de "`.
- `minute`
The string used for the minute, e.g., `"00"`.
- `month`
The string used for the month, e.g., `"12"`.
- `second`
The string used for the second, e.g., `"07"` or `"42"`.
- `zone`
The string used for the name of the time zone, e.g., `"EST".`
- `weekday`
The string used for the weekday, e.g., `"M"`, `"Monday"`, `"Montag".`
- `year`
The string used for the year, e.g., `"2012"`, `"96".`
### Example
Prior to using any date methods, you must load `cldr/main/{locale}/ca-gregorian.json`, `cldr/main/{locale}/timeZoneNames.json`, `cldr/supplemental/timeData.json`, `cldr/supplemental/weekData.json`, and the CLDR content required by the number module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.dateToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter();
formatter( new Date( 2010, 10, 30 ) );
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
```
You can use the instance method `.dateToPartsFormatter()`, which uses the instance locale.
```javascript
var enFormatter = Globalize( "en" ).dateToPartsFormatter(),
deFormatter = Globalize( "de" ).dateToPartsFormatter();
enFormatter( new Date( 2010, 10, 30 ) );
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
deFormatter( new Date( 2010, 10, 30 ) );
// > [
// { type: 'day', value: '30' },
// { type: 'literal', value: '.' },
// { type: 'month', value: '11' },
// { type: 'literal', value: '.' },
// { type: 'year', value: '2010' }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter({datetime: "short"});
formatter( new Date( 2010, 10, 30, 17, 55 ) ).map(({type, value}) => {
switch ( type ) {
case "year": return `<strong>${value}</strong>`;
default: return value;
}
}).join( "" );
// > "11/30/<strong>10</strong>, 5:55 PM"
```
Please, see [.dateFormatter() example](./date-formatter.md#example) for additional examples such as using `date`, `time`, `datetime`, and `skeleton` options.
For improved performance on iterations, first create the formatter. Then, reuse it on each loop.
```javascript
// In an application, this array could have a few hundred entries
var dates = [ new Date( 2010, 10, 30, 17, 55 ), new Date( 2015, 3, 18, 4, 25 ) ];
var formatter = Globalize( "en" ).dateToPartsFormatter({ time: "short" });
var formattedDates = dates.map(function( date ) {
return formatter( date );
});
// > [
// [
// { "type": "hour", "value": "5" },
// { "type": "literal", "value": ":" },
// { "type": "minute", "value": "55" },
// { "type": "literal", "value": " " },
// { "type": "dayperiod", "value": "PM" }
// ],
// [
// { "type": "hour", "value": "4" },
// { "type": "literal", "value": ":" },
// { "type": "minute", "value": "25" },
// { "type": "literal", "value": " " },
// { "type": "dayperiod", "value": "AM" }
// ]
// ]
```

View File

@@ -1,29 +0,0 @@
## Globalize.loadTimeZone( ianaTzData )
This method allows you to load IANA time zone data to enable `options.timeZone` feature on date formatters and parsers.
### Parameters
#### ianaTzData
A JSON object with zdumped IANA timezone data. Get the data via [`iana-tz-data`](https://github.com/rxaviers/iana-tz-data).
### Example
```javascript
Globalize.loadTimeZone({
"zoneData": {
...
"America": {
...
"New_York": {
abbrs: [],
untils: [],
offsets: [],
isdsts: []
}
...
}
}
});
```

View File

@@ -1,105 +0,0 @@
## .loadMessages( json )
Load messages data.
The first level of keys must be locales. For example:
```
{
en: {
hello: "Hello"
},
pt: {
hello: "Olá"
}
}
```
ICU MessageFormat pattern is supported: variable replacement, gender and plural inflections. For more information see [`.messageFormatter( path ) ➡ function([ variables ])`](./message-formatter.md).
The provided messages are stored along side other cldr data, under the "globalize-messages" key. This allows Globalize to reuse the traversal methods provided by cldrjs. You can inspect this data using `cldrjs.get("globalize-messages")`.
### Parameters
#### json
JSON object of messages data. Keys can use any character, except `/`, `{` and `}`. Values (i.e., the message content itself) can contain any character.
### Example
```javascript
Globalize.loadMessages({
pt: {
greetings: {
hello: "Olá",
bye: "Tchau"
}
}
});
Globalize( "pt" ).formatMessage( "greetings/hello" );
// > Olá
```
#### Multiline strings
Use Arrays as a convenience for multiline strings. The lines will be joined by a space.
```javascript
Globalize.loadMessages({
en: {
longText: [
"Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi non",
"quis exercitationem culpa nesciunt nihil aut nostrum explicabo",
"reprehenderit optio amet ab temporibus asperiores quasi cupiditate.",
"Voluptatum ducimus voluptates voluptas?"
]
}
});
Globalize( "en" ).formatMessage( "longText" );
// > "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi non quis exercitationem culpa nesciunt nihil aut nostrum explicabo reprehenderit optio amet ab temporibus asperiores quasi cupiditate. Voluptatum ducimus voluptates voluptas?"
```
#### Messages inheritance
It's possible to inherit messages, for example:
```javascript
Globalize.loadMessages({
root: {
amen: "Amen"
},
de: {},
en: {},
"en-GB": {},
fr: {},
pt: {
amen: "Amém"
},
"pt-PT": {}
});
Globalize( "de" ).formatMessage( "amen" );
// > "Amen"
Globalize( "en" ).formatMessage( "amen" );
// > "Amen"
Globalize( "en-GB" ).formatMessage( "amen" );
// > "Amen"
Globalize( "fr" ).formatMessage( "amen" );
// > "Amen"
Globalize( "pt-PT" ).formatMessage( "amen" );
// > "Amém"
```
Note that `de`, `en`, `en-GB`, `fr`, and `pt-PT` are empty. `.formatMessage()` inherits `pt-PT` messages from `pt` (`pt-PT``pt`), and it inherits the other messages from root, eg. `en-GB``en-001``en``root`. Yes, `root` is the last bundle of the parent lookup.
Attention: On browsers, message inheritance only works if the optional dependency `cldr/unresolved` is loaded.
```html
<script src="cldr/unresolved.js"></script>
```

View File

@@ -1,208 +0,0 @@
## .messageFormatter( path ) ➡ function([ variables ])
Return a function that formats a message (using ICU message format pattern) given its path and a set of variables into a user-readable string. It supports pluralization and gender inflections.
Use [`Globalize.loadMessages( json )`](./load-messages.md) to load
messages data.
### Parameters
#### path
String or Array containing the path of the message content, eg., `"greetings/bye"`, or `[ "greetings", "bye" ]`.
#### variables
Optional. Variables can be Objects, where each property can be referenced by name inside a message; or Arrays, where each entry of the Array can be used inside a message, using numeric indices. When passing one or more arguments of other types, they're converted to an Array and used as such.
### Example
You can use the static method `Globalize.messageFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.loadMessages({
pt: {
greetings: {
bye: "Tchau"
}
}
});
Globalize.locale( "pt" );
formatter = Globalize.messageFormatter( "greetings/bye" );
formatter();
// > "Tchau"
```
You can use the instance method `.messageFormatter()`, which uses the instance locale.
```javascript
var pt = new Globalize( "pt" ),
formatter = pt.messageFormatter( "greetings/bye" );
formatter();
// > "Tchau"
```
#### Simple Variable Replacement
```javascript
var formatter;
Globalize.loadMessages({
en: {
hello: "Hello, {0} {1} {2}",
hey: "Hey, {first} {middle} {last}"
}
});
formatter = Globalize( "en" ).messageFormatter( "hello" );
// Numbered variables using Array.
formatter([ "Wolfgang", "Amadeus", "Mozart" ]);
// > "Hello, Wolfgang Amadeus Mozart"
// Numbered variables using function arguments.
formatter( "Wolfgang", "Amadeus", "Mozart" );
// > "Hello, Wolfgang Amadeus Mozart"
// Named variables using Object key-value pairs.
formatter = Globalize( "en" ).messageFormatter( "hey" );
formatter({
first: "Wolfgang",
middle: "Amadeus",
last: "Mozart"
});
// > "Hey, Wolfgang Amadeus Mozart"
```
#### Gender inflections
`select` can be used to format any message variations that works like a switch.
```javascript
var formatter;
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
party: [
"{hostGender, select,",
" female {{host} invites {guest} to her party}",
" male {{host} invites {guest} to his party}",
" other {{host} invites {guest} to their party}",
"}"
]
}
});
formatter = Globalize( "en" ).messageFormatter( "party" );
formatter({
guest: "Mozart",
host: "Beethoven",
hostGender: "male"
});
// > "Beethoven invites Mozart to his party"
```
#### Plural inflections
It uses the plural forms `zero`, `one`, `two`, `few`, `many`, or `other` (required). Note English only uses `one` and `other`. So, including `zero` will never get called, even when the number is 0. For more information see [`.pluralGenerator()`](../plural/plural-generator.md).
```javascript
var numberFormatter, taskFormatter,
en = new Globalize( "en" );
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
task: [
"You have {count, plural,",
" one {one task}",
" other {{formattedCount} tasks}",
"} remaining"
]
}
});
numberFormatter = en.numberFormatter();
taskFormatter = en.messageFormatter( "task" );
taskFormatter({
count: 1000,
formattedCount: numberFormatter( 1000 )
});
// > "You have 1,000 tasks remaining"
```
Literal numeric keys can be used in `plural` to match single, specific numbers.
```javascript
var taskFormatter,
en = new Globalize( "en" );
// Note you can define multiple lines message using an Array of Strings.
Globalize.loadMessages({
en: {
task: [
"You have {count, plural,",
" =0 {no tasks}",
" one {one task}",
" other {{formattedCount} tasks}",
"} remaining"
]
}
});
taskFormatter = Globalize( "en" ).messageFormatter( "task" );
taskFormatter({
count: 0,
formattedCount: en.numberFormatter( 0 )
});
// > "You have no tasks remaining"
```
You may find useful having the plural forms calculated with an offset applied.
Use `#` to output the resulting number. Note literal numeric keys do NOT use the
offset value.
```javascript
var likeFormatter,
en = new Globalize( "en" );
Globalize.loadMessages({
en: {
likeIncludingMe: [
"{0, plural, offset:1",
" =0 {Be the first to like this}",
" =1 {You liked this}",
" one {You and someone else liked this}",
" other {You and # others liked this}",
"}"
]
}
});
likeFormatter = Globalize( "en" ).messageFormatter( "likeIncludingMe" );
likeFormatter( 0 );
// > "Be the first to like this"
likeFormatter( 1 );
// > "You liked this"
likeFormatter( 2 );
// > "You and someone else liked this"
likeFormatter( 3 );
// > "You and 2 others liked this"
```
Read on [SlexAxton/messageFormatter.js][] for more information on regard of ICU MessageFormat.
[SlexAxton/messageFormatter.js]: https://github.com/SlexAxton/messageformat.js/#no-frills

View File

@@ -1,202 +0,0 @@
## .numberFormatter( [options] ) ➜ function( value )
Return a function that formats a number according to the given options.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### options.style
Optional. String `decimal` (default), or `percent`.
#### options.minimumIntegerDigits
Optional. Non-negative integer Number value indicating the minimum integer digits to be used. Numbers will be padded with leading zeroes if necessary.
#### options.minimumFractionDigits, options.maximumFractionDigits
Optional. Non-negative integer Number values indicating the minimum and maximum fraction digits to be used. Numbers will be rounded or padded with trailing zeroes if necessary. Either one or both of these properties must be present. If they are, they will override minimum and maximum fraction digits derived from the CLDR patterns.
#### options.minimumSignificantDigits, options.maximumSignificantDigits
Optional. Positive integer Number values indicating the minimum and maximum fraction digits to be shown. Either none or both of these properties are present. If they are, they override minimum and maximum integer and fraction digits. The formatter uses however many integer and fraction digits are required to display the specified number of significant digits.
#### options.round
Optional. String with rounding method `ceil`, `floor`, `round` (default), or `truncate`.
#### options.useGrouping
Optional. Boolean (default is true) value indicating whether a grouping separator should be used.
#### options.compact
Optional. String `short` or `long` indicating which compact number format should be used to represent the number.
### Examples
#### Static Formatter
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.numberFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.numberFormatter();
formatter( 3.141592 );
// > "3.142"
```
#### Instance Formatter
You can use the instance method `.numberFormatter()`, which uses the instance
locale.
```javascript
var arFormatter = Globalize( "ar" ).numberFormatter(),
esFormatter = Globalize( "es" ).numberFormatter(),
zhFormatter = Globalize( "zh-u-nu-native" ).numberFormatter();
arFormatter( 3.141592 );
// > "٣٫١٤٢"
esFormatter( 3.141592 );
// > "3,142"
zhFormatter( 3.141592 );
// > "三.一四二"
```
#### Configuring decimal places
The number of decimal places can be decreased or increased using `minimumFractionDigits` and `maximumFractionDigits`.
```javascript
Globalize.numberFormatter({ maximumFractionDigits: 2 })( 3.141592 );
// > "3.14"
Globalize.numberFormatter({ minimumFractionDigits: 2 })( 1.5 );
// > "1.50"
```
#### Configuring significant digits
The number of significant (non-zero) digits can be decreased or increased using `minimumSignificantDigits` and `maximumSignificantDigits`.
```javascript
var formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 3.141592 );
// > "3.14"
formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 12345 );
// > "12,300"
formatter = Globalize.numberFormatter({
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
formatter( 0.00012345 );
// > "0.000123"
```
#### Formatting Percentages
Numbers can be formatted as percentages.
```javascript
var enFormatter = Globalize( "en" ).numberFormatter({
style: "percent",
minimumFractionDigits: 1,
maximumFractionDigits: 1
});
var frFormatter = Globalize( "fr" ).numberFormatter({
style: "percent",
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
enFormatter( 0.0016 );
// > "0.2%"
enFormatter( 0.0014 );
// > "0.1%"
frFormatter( 0.0005 );
// > "0,05 %"
```
#### Formatting Compact Numbers
Long numbers can be represented in a compact format, with `short` using abbreviated units and `long` using the full unit name.
```javascript
var shortFormatter = Globalize( "en" ).numberFormatter({
compact: "short"
});
var longFormatter = Globalize( "en" ).numberFormatter({
compact: "long"
});
shortFormatter( 27588910 );
// > "28M"
longFormatter( 27588910 );
// > "28 million"
```
The minimumSignificantDigits and maximumSignificantDigits options are specially useful to control the number of digits to display.
```js
Globalize( "en" ).formatNumber( 27588910, {
compact: "short",
minimumSignificantDigits: 3,
maximumSignificantDigits: 3
});
// > "27.6M"
```
#### Configuring Rounding
Numbers with a decreased amount of decimal places can be rounded up, rounded down, rounded arithmetically, or truncated by setting the `round` option to `ceil`, `floor`, `round` (default), or `truncate`.
```javascript
var formatter = Globalize.numberFormatter({
maximumFractionDigits: 2,
round: "ceil"
});
formatter( 3.141592 );
// > "3.15"
```
#### Performance Suggestions
For improved performance on iterations, the formatter should be created before the loop. Then, it can be reused in each iteration.
```javascript
var numbers = [ 1, 1, 2, 3, ... ];
var formatter = Globalize( "en" ).numberFormatter();
formattedNumbers = numbers.map(function( number ) {
return formatter( number );
});
```

View File

@@ -1,130 +0,0 @@
## .numberParser( [options] ) ➜ function( value )
Return a function that parses a String representing a number according to the given options. If value is invalid, `NaN` is returned.
The returned function is invoked with one argument: the String representing a number `value` to be parsed.
### Parameters
#### options
See [.numberFormatter() options](./number-formatter.md#parameters).
#### value
String with number to be parsed, eg. `"3.14"`.
### Example
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.numberParser()`, which uses the default locale.
```javascript
var parser;
Globalize.locale( "en" );
parser = Globalize.numberParser();
parser( "3.14" );
// > 3.14
```
You can use the instance method `.numberParser()`, which uses the instance locale.
```javascript
var enParser = Globalize( "en" ).numberParser(),
esParser = Globalize( "es" ).numberParser();
enParser( "3.14" );
// > 3.14
esParser( "3,14" );
// > 3.14
```
Some more examples.
```javascript
var enParser = Globalize( "en" ).numberParser();
enParser( "12,735" );
// > 12735
enParser( "12,735.00" );
// > 12735
Globalize( "en" ).numberParser({ style: "percent" })( "100%" );
// > 1
enParser( "∞" );
// > Infinity
enParser( "-3" );
// > -3
enParser( "-∞" );
// > -Infinity
enParser( "invalid-stuff" );
// > NaN
enParser( "invalid-stuff-that-includes-number-123" );
// > NaN
enParser( "invalid-stuff-123-that-includes-number" );
// > NaN
enParser( "123-invalid-stuff-that-includes-number" );
// > NaN
// Invalid decimal separator. (note `.` is used as decimal separator for English)
enParser( "3,14" );
// > NaN
// Invalid grouping separator position.
enParser( "127,35.00" );
// > NaN
```
Loose matching examples.
```js
var svParser = Globalize( "sv" ).numberParser();
// Swedish uses NO-BREAK-SPACE U+00A0 as grouping separator.
svParser( "1\xA0000,50" );
// > 1000.5
// The parser is lenient and accepts various space characters like regular space
// SPACE U+0020. Technically, it accepts any character of the Unicode general
// category [:Zs:].
svParser( "1 000,50" );
// > 1000.5
var fiParser = Globalize( "fi" ).numberParser();
// Finish uses MINUS SIGN U+2212 for the minus sign.
fiParser( "\u22123" );
// > -3
// The parser is lenient and accepts various hyphen characters like regular
// HYPHEN-MINUS U+002D. Technically, it accepts any character of the Unicode
// general category [:Dash:].
fiParser( "-3" );
// > -3
```
For improved performance on iterations, first create the parser. Then, reuse it
on each loop.
```javascript
var formattedNumbers = [ "1", "1", "2", "3", ... ];
var parser = Globalize( "en" ).numberParser();
numbers = formattedNumbers.map(function( formattedNumber ) {
return parser( formattedNumber );
});
```

View File

@@ -1,140 +0,0 @@
## .numberToPartsFormatter( [options] ) ➜ function( value )
Return a function that formats a number into parts tokens according to the given options.
The returned function is invoked with one argument: the Number `value` to be formatted.
### Parameters
#### options
Please, see [.numberFormatter() options](./number-formatter.md#parameters).
### Returns
An Array of objects containing the formatted number in parts. The returned structure looks like this:
- `decimal`
The decimal separator string, e.g., `"."`.
- `fraction`
The fraction number.
- `group`
The group separator string, e.g., `","`.
- `infinity`
The Infinity string, e.g., `"∞"`.
- `integer`
The integer number.
- `literal`
Any literal strings or whitespace in the formatted number.
- `minusSign`
The minus sign string, e.g., `"-"`.
- `nan`
The NaN string, e.g., `"NaN"`.
- `plusSign`
The plus sign string, e.g., `"+"`.
- `percentSign`
The percent sign string, e.g., `"%"`.
- `compact`
The compact string, e.g., `"thousand"`.
### Examples
Prior to using any number methods, you must load `cldr/main/{locale}/numbers.json` and `cldr/supplemental/numberingSystems.json`. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
#### Static Formatter
You can use the static method `Globalize.numberToPartsFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.numberToPartsFormatter();
formatter( 3.141592 );
// > [
// { "type": "integer", "value": "3" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "142" }
// ]
```
#### Instance Formatter
You can use the instance method `.numberFormatter()`, which uses the instance
locale.
```javascript
var arFormatter = Globalize( "ar" ).numberToPartsFormatter(),
esFormatter = Globalize( "es" ).numberToPartsFormatter(),
zhFormatter = Globalize( "zh-u-nu-native" ).numberToPartsFormatter();
arFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "٣" },
// { "type": "decimal", "value": "٫" },
// { "type": "fraction", "value": "١٤٢" }
// ]
esFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "3" },
// { "type": "decimal", "value": "," },
// { "type": "fraction", "value": "142" }
// ]
zhFormatter( 3.141592 );
// > [
// { "type": "integer", "value": "三" },
// { "type": "decimal", "value": "." },
// { "type": "fraction", "value": "一四二" }
// ]
```
The information is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`][], [arrow functions][], a [switch statement][], [template literals][], and [`Array.prototype.reduce()`][].
[`Array.prototype.map()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
[arrow functions]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
[switch statement]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch
[template literals]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
[`Array.prototype.reduce()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
#### More Examples
Please, see [.numberFormatter() example](./number-formatter.md#example) for additional examples such as configuring decimal places, significant digits, percentages, and compact numbers.
#### Performance Suggestions
For improved performance on iterations, the formatter should be created before the loop. Then, it can be reused in each iteration.
```javascript
var numbers = [ 1, 1, 2, 3, ... ];
var formatter = Globalize( "en" ).numberFormatter();
formattedNumbers = numbers.map(function( number ) {
return formatter( number );
});
```

View File

@@ -1,84 +0,0 @@
## .pluralGenerator( [options] ) ➜ function( value )
It supports the creation of internationalized messages with plural inflection by returning a function that returns the value's plural group: `zero`, `one`, `two`, `few`, `many`, or `other`.
The returned function is invoked with one argument: the Number `value` for which to return the plural group.
### Parameters
#### options.type
Optional. String `cardinal` (default), or `ordinal`.
#### value
A Number for which to return the plural group.
### Example
Prior to using any plural method, you must load either `supplemental/plurals.json` for cardinals or `supplemental/ordinals.json` for ordinals.
Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.pluralGenerator()`, which uses the default locale.
```javascript
var plural;
Globalize.locale( "en" );
// Cardinals
plural = Globalize.pluralGenerator();
plural( 0 );
// > "other"
plural( 1 );
// > "one"
plural( 2 );
// > "other"
// Ordinals
plural = Globalize.pluralGenerator({ type: "ordinal" });
plural( 0 );
// > "other"
plural( 1 );
// > "one"
plural( 2 );
// > "two"
```
You can use the instance method `.pluralGenerator()`, which uses the instance locale.
```javascript
var plural = Globalize( "zh" ).pluralGenerator();
plural( 1 );
// > "other"
```
For comparison (cardinals):
| | en (English) | ru (Russian) | ar (Arabic) |
| ------------- | ------------ | ------------ | ----------- |
| `plural( 0 )` | `other` | `many` | `zero` |
| `plural( 1 )` | `one` | `one` | `one` |
| `plural( 2 )` | `other` | `few` | `two` |
| `plural( 3 )` | `other` | `few` | `few` |
| `plural( 5 )` | `other` | `many` | `few` |
For comparison (ordinals):
| | en (English) | ru (Russian) | ar (Arabic) |
| ---------------------------------- | ------------ | ------------ | ----------- |
| `plural( 0, { type: "ordinal" } )` | `other` | `other` | `other` |
| `plural( 1, { type: "ordinal" } )` | `one` | `other` | `other` |
| `plural( 2, { type: "ordinal" } )` | `two` | `other` | `other` |
| `plural( 3, { type: "ordinal" } )` | `few` | `other` | `other` |
| `plural( 5, { type: "ordinal" } )` | `other` | `other` | `other` |

View File

@@ -1,60 +0,0 @@
## .relativeTimeFormatter( unit [, options] ) ➜ function( value )
Returns a function that formats a relative time according to the given unit, options, and the default/instance locale.
The returned function is invoked with one argument: the number `value` to be formatted.
### Parameters
#### unit
String value indicating the unit to be formatted. eg. "day", "week", "month", etc.
#### options.form
String, e.g., `"short"` or `"narrow"`, or falsy for default long form.
#### value
The number to be formatted.
### Example
Prior to using any relative time methods, you must load `cldr/main/{locale}/dateFields.json` and the CLDR content required by the number and plural modules. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.relativeTimeFormatter()`, which uses the default locale.
```javascript
var formatter;
Globalize.locale( "en" );
formatter = Globalize.relativeTimeFormatter( "month" );
formatter( 1 );
// > "next month"
formatter( 3 );
// > "in 3 months"
formatter( -1 );
// > "last month"
formatter( -3 );
// > "3 months ago"
```
You can use the instance method `.relativeTimeFormatter()`, which uses the instance locale.
```javascript
var globalize = new Globalize( "en" ),
formatter = globalize.relativeTimeFormatter( "week" );
formatter( 1 );
// > "next week"
```

View File

@@ -1,72 +0,0 @@
## .unitFormatter( unit [, options] ) ➜ function( value )
Returns a function that formats a unit according to the given unit, options, and the default/instance locale.
The returned function is invoked with one argument: the number `value` to be formatted.
### Parameters
#### unit
String value indicating the unit to be formatted. eg. "day", "week", "month", etc. Could also be a compound unit, eg. "mile-per-hour" or "mile/hour"
#### options.form
Optional. String, e.g., `"long"` (default), `"short"` or `"narrow"`.
#### options.numberFormatter
Optional. A number formatter function. Defaults to `Globalize.numberFormatter()` for the current locale using the default options.
#### value
The number to be formatted.
### Example
Prior to using any unit methods, you must load `cldr/main/{locale}/units.json` and the CLDR content required by the plural module. Read [CLDR content][] if you need more information.
[CLDR content]: ../../../README.md#2-cldr-content
You can use the static method `Globalize.unitFormatter()`, which uses the default locale.
```javascript
var customNumberFormatter, formatter;
Globalize.locale( "en" );
formatter = Globalize.unitFormatter( "month", { form: "long" } );
formatter( 1 );
// > "1 month"
formatter( 3 );
// > "3 months"
formatter( 3000 );
// > "3,000 months"
```
You can pass a custom number formatter to format the number of units.
```javascript
var customNumberFormatter, formatter;
Globalize.locale( "en" );
customNumberFormatter = Globalize.numberFormatter({ useGrouping = false })
formatter = Globalize.unitFormatter( "mile-per-hour", {
form: "narrow", numberFormatter: customNumberFormatter
} );
formatter(5000)
// > "5000mph"
```
You can use the instance method `.unitFormatter()`, which uses the instance locale.
```javascript
var globalize = new Globalize( "en" ),
formatter = globalize.unitFormatter( "mile-per-hour", { form: "narrow" } );
formatter( 10 );
// > "10mph"
```

View File

@@ -1,177 +0,0 @@
# Globalize 1.3.0 announcement
On July 3rd, we released Globalize 1.3.0. It is a special release, because it includes some very useful feature enhancements to support advanced date, time, timezone manipulation, and other long due fixes. We wanted to share more details on these improvements.
## IANA/Olson Time Zone Support
> This change was contributed by Kandaswamy Manikandan @rajavelmani (PayPal) and Rafael Xavier @rxaviers in #687 and #701.
In previous versions, Globalize had some partial time zone support for a user's runtime time zone. However specific CLDR patterns (`z`, `v`, and `V`) that display strings such as `PDT`, `Pacific Daylight Time`, `Pacific Time`, and `Los Angeles Time` could not be displayed. The challenge [we had](https://github.com/globalizejs/globalize/pull/202) to determine how costly a solution would be to provide full IANA/Olson time zone support due to the additional manipulation code and data (i.e., IANA database). Therefore, in the past, we encouraged users that needed to manipulate date in arbitrary time zones to use a separate library, like *moment-timezone*. Nevertheless, this solution never closed the gap between internationalization (i18n) implementations leveraging CLDR and having full maneuverability of time zones.
With the latest release 1.3.0, Globalize fully supports time zone. Simply put, by using Globalize 1.3.0, you now have full IANA support with the strength of CLDR for i18n!
```js
Globalize.locale("en");
let date = new Date();
Globalize.formatDate(date, {datetime: "short", timeZone: "America/Los_Angeles"});
// > '3/19/17, 3:19 PM'
Globalize.formatDate(date, {datetime: "short", timeZone: "America/New_York"});
// > '3/19/17, 6:19 PM'
Globalize.formatDate(date, {datetime: "short", timeZone: "America/Sao_Paulo"});
// > '3/19/17, 7:19 PM'
Globalize.formatDate(date, {datetime: "short", timeZone: "Europe/Berlin"});
// > '3/19/17, 11:19 PM'
Globalize.formatDate(date, {datetime: "full", timeZone: "America/Los_Angeles"});
// > 'Sunday, March 19, 2017 at 3:19:22 PM Pacific Daylight Time'
Globalize.formatDate(date, {datetime: "full", timeZone: "America/New_York"});
// > 'Sunday, March 19, 2017 at 6:19:22 PM Eastern Daylight Time'
Globalize.formatDate(date, {datetime: "full", timeZone: "America/Sao_Paulo"});
// > 'Sunday, March 19, 2017 at 7:19:22 PM Brasilia Standard Time'
Globalize.formatDate(date, {datetime: "full", timeZone: "Europe/Berlin"});
// > 'Sunday, March 19, 2017 at 11:19:22 PM Central European Standard Time'
Globalize("pt").formatDate(date, {datetime: "full", timeZone: "America/Sao_Paulo"});
// > 'domingo, 19 de março de 2017 19:19:22 Horário Padrão de Brasília'
Globalize("de").formatDate(date, {datetime: "full", timeZone: "Europe/Berlin"});
// > 'Sonntag, 19. März 2017 um 23:19:22 Mitteleuropäische Normalzeit'
Globalize("zh").formatDate(date, {datetime: "full", timeZone: "Asia/Shanghai"});
// > '2017年3月20日星期一 中国标准时间 上午6:19:22'
Globalize("ar").formatDate(date, {datetime: "full", timeZone: "Africa/Cairo"});
// > 'الاثنين، ٢٠ مارس، ٢٠١٧ ١٢:١٩:٢٢ ص توقيت شرق أوروبا الرسمي'
```
We have solved this in a low footprint, high performance implementation using [zoned-date-time](https://github.com/rxaviers/zoned-date-time) under the hoods, which is a 0.6KB library for the time zone manipulations. We have leveraged the Globalize Compiler for precompling the IANA data base for production. For example, let's say you are serving content in English (e.g. locale en-US) for America/Los_Angeles time using the following formatter:
```js
var dateWithTimeZoneFormatter = Globalize.dateFormatter({
datetime: "full",
timeZone: "America/Los_Angeles"
});
```
The final size (for production) of this code will be:
| filename | minified+gzipped size |
| ---------------------------------------- | --------------------- |
| i18n/en.js (includes CLDR and IANA data) | 1.7KB |
| core, number, and date globalize runtime lib + zoned-date-time | 7.0KB |
See globalize [compiler example](https://github.com/globalizejs/globalize/tree/master/examples/globalize-compiler) or [app-npm-webpack example](https://github.com/globalizejs/globalize/tree/master/examples/app-npm-webpack) for details.
## Format Date To Parts
> This change was contributed by Reza Payami @rpayami (PayPal) and Rafael Xavier @rxaviers in #697 and #700.
Modern user interfaces often need to manipulate the date format output, which is impossible via the existing format function that returns an opaque string. Making any attempt to do this can break internationalization support. [Ecma-402](https://github.com/tc39/ecma402/) has recently added [`Intl.DateTimeFormat.prototype.formatToParts`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts) to fulfill that purpose, which at the time of this post, is at stage 4 and is implemented by latest Firefox and Chrome.
In Globalize, we introduced [`.dateToPartsFormatter`](https://github.com/globalizejs/globalize/blob/master/doc/api/date/date-to-parts-formatter.md) and [`.formatDateToParts`](https://github.com/globalizejs/globalize/blob/master/doc/api/date/date-to-parts-formatter.md).
```js
Globalize.locale( "en" );
Globalize.formatDateToParts(new Date(2010, 10, 30));
// > [
// { "type": "month", "value": "11" },
// { "type": "literal", "value": "/" },
// { "type": "day", "value": "30" },
// { "type": "literal", "value": "/" },
// { "type": "year", "value": "2010" }
// ]
```
The data is available separately and it can be formatted and concatenated again in a customized way. For example by using [`Array.prototype.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions), a [switch statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch), [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), and [`Array.prototype.reduce()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce).
```js
let formatter;
Globalize.locale( "en" );
formatter = Globalize.dateToPartsFormatter({datetime: "short"});
formatter( new Date( 2010, 10, 30, 17, 55 ) ).map(({type, value}) => {
switch ( type ) {
case "year": return `<strong>${value}</strong>`;
default: return value;
}
}).join( "" );
// > "11/30/<strong>10</strong>, 5:55 PM"
```
See [React Date Input](https://github.com/rxaviers/react-date-input) as a demo of a UI component for React optimized for i18n and a11y.
| Localized and smart date input | Feb 28 in `en`, `es`, `pt`, `de`, `zh`, `ko`, and `ar` |
| ---------------------------------------- | ---------------------------------------- |
| ![en](https://media.giphy.com/media/xUA7aZAUNINGP2jI4M/giphy.gif) | ![en-es-pt-de-zh-ko-ar](https://media.giphy.com/media/3og0ILQu0KxLRewJnW/giphy.gif) |
## Dynamically Augmented Date Skeletons
> This change was contributed by Marat Dyatko @vectart and Artur Eshenbrener @Strate in #462 and #604.
The style used to display a date format often varies depending on the application. CLDR offers data for certain presets like short (e.g., short date `"7/1/17"`), medium (e.g., medium date `"Jul 1, 2017"`), long (e.g., long date `"July 1, 2017"`), and full (e.g., full date `"Saturday, July 1, 2017"`). Although, we may want something different such as `"Jul 1"`. For that CLDR offers data for individual [date fields](http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table) and their combinations, which are used by Globalize to synthesize an open-ended list of custom formats (called skeletons). But, what's interesting is that it would be prohibitively large if CLDR provided data for every single possible combination. So, there's an algorithm specified by [UTS#35](http://www.unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems) to deduce missing data from the requested format.
For the `"Jul 1"` example, we should use `{skeleton: "MMMd"}`. Internally, Globalize finds a direct match in CLDR for the requested skeleton. This works fine in previous Globalize versions.
For that next example, let's assume we want `"July 1"`, i.e., `{skeleton: "MMMMd"}`. Internally, Globalize doesn't find a direct match in CLDR. For this skeleton, Globalize needs to use the data for `MMMd`, which maps to `"MMM d"` in the English case, and then it needs to replace `MMM` with `MMMM` dynamically generating `"MMMM d"`. This doesn't work in previous versions of Globalize, but it works now on latest v1.3.0.
If we wanted `"07/01"` instead, we should use `{skeleton: "MMdd"}`. Internally, Globalize doesn't find a direct match in CLDR for this skeleton and, therefore, it fais in globalize v1.2.3. Globalize needs to use the data for `Md`, which in the case of English maps to `"M/d"`, and then replace `M` wtih `MM` and `d` with `dd` dynamically generating `"MM/dd"`.
To make a long story short, the algorithm in globalize v1.3.0 has been significantly improved and it allows using virtually any skeletons.
```js
// A skeleton not directly found in CLDR and that needs to be deduced by globalize.
// In English, globalize needs to use the data for GyMMMEd, and adjust MMM with MMMM,
// and E with EEEE. Then, it needs to find the data for hms and glue them together
// using the appropriate format.
// On globalize v1.2.3, an error is thrown saying this skeleton wasn't found.
let skeleton = "GyMMMMEEEEdhms";
Globalize("en").formatDate(new Date(), {skeleton});
// > 'Saturday, July 1, 2017 AD at 4:58:27 PM'
Globalize("pt").formatDate(new Date(), {skeleton});
// > 'sábado, 1 de julho de 2017 d.C. 5:01:20 PM'
Globalize("de").formatDate(new Date(), {skeleton});
// > 'Samstag, 1. Juli 2017 n. Chr. um 5:01:33 nachm.'
Globalize("zh").formatDate(new Date(), {skeleton});
// > '公元2017年七月月1日星期六 下午5:01:35'
Globalize("ko").formatDate(new Date(), {skeleton});
// > 'AD 2017년 7월 1일 토요일 오후 5:01:38'
Globalize("ar").formatDate(new Date(), {skeleton});
// > 'السبت، ١ يوليو، ٢٠١٧ م ٥:٠١:٤٠ م'
Globalize("ar-MA").formatDate(new Date(), {skeleton});
// > 'السبت، 1 يوليوز، 2017 م 5:04:29 م'
Globalize("it").formatDate(new Date(), {skeleton});
// > 'sabato 1 luglio 2017 d.C. 5:01:52 PM'
```
Read our [getting started](https://github.com/globalizejs/globalize/#getting-started) and play with it yourself.
## Other Enhancements and Bug Fixes
🎉 Enhancements
- Date: Show timezone offset optional minutes for O pattern (e.g., GMT-6:30 note the :30) [#339](https://github.com/globalizejs/globalize/pull/339) (via PR [#729](https://github.com/globalizejs/globalize/pull/729)) (Rafael Xavier)
- Date: Show timezone offset optional minutes and seconds for x and X patterns (e.g., -06:30 note the :30) [#339](https://github.com/globalizejs/globalize/pull/339) (via PR [#729](https://github.com/globalizejs/globalize/pull/729)) (Rafael Xavier)
- Date: Assert options.skeleton (PR [#726](https://github.com/globalizejs/globalize/pull/726)) (Rafael Xavier)
- Date parser: Make runtime phase lighter [#735](https://github.com/globalizejs/globalize/pull/735) (Rafael Xavier)
- Date parser: Loose Matching PR [#730](https://github.com/globalizejs/globalize/pull/730) (Rafael Xavier)
- Allows, among others, parsing arabic dates as user types them (i.e., without control characters)
- Number formatter: Amend integer and fraction formatter for small numbers like 1e-7 [#750](https://github.com/globalizejs/globalize/pull/750) (Rafael Xavier)
- Number parser: Lenient about trailing decimal separator [#744](https://github.com/globalizejs/globalize/pull/744) (Rafael Xavier)
- Runtime: Use strict [#676](https://github.com/globalizejs/globalize/pull/676) (Zack Birkenbuel)
🐛 Fixes
- Date parser: invalid output by mixing numbering systems [#696](https://github.com/globalizejs/globalize/pull/696) (via PR [#733](https://github.com/globalizejs/globalize/pull/733)) (Rafael Xavier)
- Date parser: fails on Turkish full datetime with Monday or Saturday [#690](https://github.com/globalizejs/globalize/pull/690) (via PR [#732](https://github.com/globalizejs/globalize/pull/732)) (Rafael Xavier)
⚙️ Others
- Compiler tests! [#721](https://github.com/globalizejs/globalize/pull/721) (via PR [#727](https://github.com/globalizejs/globalize/pull/727)) (Nikola Kovacs)
- Documentation style refactor [#737](https://github.com/globalizejs/globalize/pull/737) (Rafael Xavier)
## Last but not least
Special thanks to other PayPal internationalization team members including Daniel Bruhn, Lucas Welti, Alolita Sharma, Mike McKenna for testing and helping integrate Globalize for PayPal products.
Special thanks to James Bellenger and Nicolas Gallagher for the React and Webpack integration enhancements for Twitter products, which certainly deserves its own blog post.
Many thanks to all of you who participated in this release by testing, reporting bugs, or submitting patches, including Jörn Zaefferer, Frédéric Miserey, Nova Patch, and whole Globalize team.

View File

@@ -1,114 +0,0 @@
# Unicode CLDR usage
## How do I get CLDR data?
*By downloading the JSON packages individually...*
Unicode CLDR is available as JSON at https://github.com/unicode-cldr/ (after this [json-packaging proposal][] took place). Please, read https://github.com/unicode-cldr/cldr-json for more information about package organization.
[json-packaging proposal]: http://cldr.unicode.org/development/development-process/design-proposals/json-packaging
*By using a package manager...*
`cldr-data` can be used for convenience. It always downloads from the correct source.
Use bower `bower install cldr-data` ([detailed instructions][]) or npm `npm install cldr-data`. For more information, see:
- https://github.com/rxaviers/cldr-data-npm
- https://github.com/rxaviers/cldr-data-bower
[detailed instructions]: https://github.com/rxaviers/cldr-data-bower
## How do I load CLDR data into Globalize?
The short answer is by using `Globalize.load()` and passing the JSON data as the first argument. Below, follow several examples on how this could be accomplished.
Example of embedding CLDR JSON data:
```html
<script>
Globalize.load({
main: {
en: {
...
}
},
supplemental: {
likelySubtags: {
...
},
timeDate: {
...
},
weekData: {
...
}
}
});
</script>
```
Example of loading it dynamically:
```html
<script src="jquery.js"></script>
<script>
// Use $.getJSON instead of $.get if your server is not configured to return the
// right MIME type for .json files.
$.when(
$.get( "cldr/main/en/ca-gregorian.json" ),
$.get( "cldr/supplemental/likelySubtags.json" ),
$.get( "cldr/supplemental/timeData.json" ),
$.get( "cldr/supplemental/weekData.json" )
).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() {
// Your code goes here.
});
</script>
```
Example using AMD (also see our [functional tests](../../test/functional.js)):
```javascript
define([
"globalize",
"json!cldr-data/main/en/ca-gregorian.json",
"json!cldr-data/supplemental/likelySubtags.json",
"json!cldr-data/supplemental/timeData.json",
"json!cldr-data/supplemental/weekData.json",
"globalize/date"
], function( Globalize, enCaGregorian, likelySubtags, timeData, weekData ) {
Globalize.load(
enCaGregorian,
likelySubtags,
timeData,
weekData
);
// Your code goes here.
});
```
Example using Node.js:
```javascript
var Globalize = require( "globalize" );
Globalize.load(
require( "cldr-data/main/en/ca-gregorian" ),
require( "cldr-data/supplemental/likelySubtags" ),
require( "cldr-data/supplemental/timeData" ),
require( "cldr-data/supplemental/weekData" )
);
```

View File

@@ -1,9 +0,0 @@
## E_DEFAULT_LOCALE_NOT_DEFINED
Thrown when any static method, eg. `Globalize.formatNumber()` is used prior to setting the Global locale with `Globalize.locale( <locale> )`.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_DEFAULT_LOCALE_NOT_DEFINED` |

View File

@@ -1,14 +0,0 @@
## E_INVALID_CLDR
Thrown when a CLDR item has an invalid or unexpected value.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_INVALID_CLDR` |
| description | Reason why the data was considered invalid |
- description "Missing rules to deduce plural form of \`{value}\`"
Thrown when the plural form (also known as plural group) is not found for the given value. This error is very unlikely to occur and is related to incomplete or invalid CLDR `supplemental/plurals-type-cardinal/{language}` data.

View File

@@ -1,12 +0,0 @@
## E_INVALID_PAR_TYPE
Thrown when a parameter has an invalid type on any static or instance methods.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_INVALID_PAR_TYPE` |
| name | Name of the invalid parameter |
| value | Invalid value |
| expected | Expected type |

View File

@@ -1,11 +0,0 @@
## E_INVALID_PAR_VALUE
Thrown for certain parameters when the type is correct, but the value is invalid. Currently, the only parameter with such validation is the date format (for either format and parse). Format allows [certain variants](../api/date/date-formatter.md#parameters), if it's none of them, error is thrown.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_INVALID_PAR_VALUE` |
| name | Name of the invalid parameter |
| value | Invalid value |

View File

@@ -1,11 +0,0 @@
## E_MISSING_CLDR
Thrown when any required CLDR item is NOT found.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_MISSING_CLDR` |
| path | Missing CLDR item path |

View File

@@ -1,10 +0,0 @@
## E_MISSING_PARAMETER
Thrown when a required parameter is missing on any static or instance methods.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_MISSING_PARAMETER` |
| name | Name of the missing parameter |

View File

@@ -1,9 +0,0 @@
## E_MISSING_PLURAL_MODULE
Thrown when plural module is needed, but not loaded, eg. formatting currencies using plural messages.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_MISSING_PLURAL_MODULE` |

View File

@@ -1,11 +0,0 @@
## E_PAR_MISSING_KEY
Thrown when a parameter misses a required key.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_PAR_MISSING_KEY` |
| key | Name of the missing parameter's key |
| name | Name of the missing parameter |

View File

@@ -1,13 +0,0 @@
## E_PAR_OUT_OF_RANGE
Thrown when a parameter is not within a valid range of values.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_PAR_OUT_OF_RANGE` |
| name | Name of the invalid parameter |
| value | Invalid value |
| minimum | Minimum value of the valid range |
| maximum | Maximum value of the valid range |

View File

@@ -1,10 +0,0 @@
## E_UNSUPPORTED
Thrown for unsupported features, eg. to format unsupported date patterns.
Error object:
| Attribute | Value |
| --- | --- |
| code | `E_UNSUPPORTED` |
| feature | Description of the unsupported feature |

View File

@@ -1,64 +0,0 @@
# Migrating from Globalize 0.x
Globalize 0.x came with a bundled locale for US English, and optional files for various other locales. Globalize 1.x uses CLDR for the locale data, and it doesn't bundle any locale data. Check out the documentation for loading CLDR data in 1.x to learn more about that. If you were only using the bundle locale, you only need to load CLDR data for US English. If you were loading other locales, make sure you load those from CLDR as well.
On the API side, things have also changed, to simplify usage, remove ambiguity and add features. The rest of this document provides a brief function-by-function list.
If you still need help with migration, let us know. We may extend this guide later as necessary.
## Globalize.addCultureInfo()
This method is replaced by `Globalize.loadMessages( json )`. If you were using it for anything except message translations, you may also need to use `Globalize.load`.
## Globalize.cultures
This property is gone. You can use Cldrjs to traverse CLDR directly.
## Globalize.culture( [locale] )
This method is replaced by the `Globalize.locale( [locale|cldr] )` method. Call it without arguments to retrieve the default locale, call it with a string argument to set the default locale.
## Globalize.findClosestCulture
This method is gone, there is no replacement. If you still need this method, create an issue with your usecase.
## Globalize.format
Replaced by three separate methods:
* `.formatNumber( value [, options] )`
* `.formatCurrency( value, currency [, options] )`
* `.formatDate( value, pattern )`
See their respective documentation for usage details. Note that the number and date formats are now based on CLDR, using the options and patterns standardized by Unicode. We don't currently have documentation for migrating these formats.
## Globalize.localize
Replaced by `.formatMessage( path [, variables ] )`. The new API is quite different and provides much more than just value-lookup. See their respective documentation for usage details.
## Globalize.parseInt/parseFloat
Replaced by `.parseNumber( value [, options] )`. So where you might have previously executed:
```js
Globalize( "en" ).parseFloat( "123,456.789" )
// > 123456.789
```
You could now execute:
```js
Globalize( "en" ).parseNumber( "123,456.789" )
// > 123456.789
```
`parseNumber` is an alias for [`.numberParser( [options] )( value )`](api/number/number-parser.md). So you could also do this:
```js
Globalize( "en" ).numberParser()( "123,456.789" )
// > 123456.789
```
## Globalize.parseDate
This method still exists, and the signature is almost the same: `.parseDate( value, pattern )`. Note that `pattern` indicates just a single "format", where Globalize 0.x supported multiple of those "formats".

View File

@@ -1,7 +0,0 @@
{
"directory": "bower_components",
"scripts": {
"preinstall": "npm install cldr-data-downloader",
"postinstall": "node ./node_modules/cldr-data-downloader/bin/download.js -i bower_components/cldr-data/index.json -o bower_components/cldr-data/"
}
}

View File

@@ -1,65 +0,0 @@
# Hello World (AMD + bower)
We assume you know what [AMD](https://github.com/amdjs/amdjs-api/wiki/AMD) and
[bower](http://bower.io/) is.
The demo is composed of the following files:
```
.
├── index.html
└── main.js
```
Before running it, execute the requirements below.
## Requirements
**1. Install Globalize**
Let's use bower to download Globalize. For more information on regard of
installation, please read [Getting Started](../../README.md#installation).
```
bower install
```
Note bower will also fetch some other dependencies of this demo, eg. require.js
and its json plugin.
You'll get this:
```
.
├── bower_components/
│ ├── globalize/
│ │ └── dist/
│ │ ├── globalize
│ │ │ ├── date.js
│ │ │ └── ...
│ │ └── globalize.js
│ └── ...
├── index.html
└── main.js
```
**2. Install Dependencies**
No action needed, because bower has already handled that for us.
**3. CLDR content**
No action needed, because bower has already handled that for us. Note `.bowerrc`
has postinstall hook that populates bower's cldr-data skeleton. For more
information, see [bower's cldr-data](https://github.com/rxaviers/cldr-data-bower).
## Running the demo
Once you've completed the requirements above:
1. Start a server by running `python -m SimpleHTTPServer` or other alternative servers such as [http-server](https://github.com/nodeapps/http-server), [nginx](http://nginx.org/en/docs/), [apache](http://httpd.apache.org/docs/trunk/).
1. Point your browser at `http://localhost:8000/`.
1. Understand the demo by reading the source code (both index.html and main.js).
We have comments there for you.

View File

@@ -1,13 +0,0 @@
{
"name": "globalize-hello-world-amd-bower",
"dependencies": {
"cldr-data": "*",
"globalize": "^1.3.0",
"iana-tz-data": "*"
},
"devDependencies": {
"requirejs": "2.1.14",
"requirejs-plugins": "1.0.2" ,
"requirejs-text": "2.0.12"
}
}

View File

@@ -1,46 +0,0 @@
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Globalize Hello World (AMD + bower)</title>
</head>
<body>
<h1>Globalize Hello World (AMD + bower)</h1>
<div id="requirements">
<h2>Requirements</h2>
<ul>
<li>Run `bower install` (you must have bower installed first).</li>
<li>Start a server, e.g., by running `python -m SimpleHTTPServer`.</li>
<li>Point your browser at `http://localhost:8000/`.</li>
<li>Please, read README.md for more information on any of the above.</li>
</ul>
</div>
<div id="demo" style="display: none">
<h2>Demo output</h2>
<p>Now: <span id="date"></span></p>
<p>Now: <span id="dateToParts"></span> (note the highlighted month, the markup was added using formatDateToParts)</p>
<p>Now (in America/Sao_Paulo): <span id="zonedDate"></span></p>
<p>A number: <span id="number"></span></p>
<p>A number (compact form): <span id="number-compact"></span></p>
<p>A currency: <span id="currency"></span></p>
<p>Plural form of <span id="plural-number"></span> is <span id="plural-form"></span></p>
<p>Messages:</p>
<ul>
<li><span id="message-0"></span></li>
<li><span id="message-1"></span></li>
<li><span id="message-2"></span></li>
<li><span id="message-3"></span></li>
</ul>
<p>Something happened: <span id="relative-time"></span></p>
<p>Speed limit: <span id="unit"></span></p>
</div>
<!--
Load require.js and let it execute main.js
-->
<script data-main="main.js" src="bower_components/requirejs/require.js"></script>
</body>
</html>

View File

@@ -1,141 +0,0 @@
/**
* 1. Configure require.js paths.
*/
require.config({
paths: {
// Globalize dependencies paths.
cldr: "./bower_components/cldrjs/dist/cldr",
// Unicode CLDR JSON data.
"cldr-data": "./bower_components/cldr-data",
// IANA time zone data.
"iana-tz-data": "../bower_components/iana-tz-data/iana-tz-data",
// require.js plugin we'll use to fetch CLDR JSON content.
json: "./bower_components/requirejs-plugins/src/json",
// text is json's dependency.
text: "./bower_components/requirejs-text/text",
// Globalize.
globalize: "./bower_components/globalize/dist/globalize"
}
});
/**
* 2. Require dependencies and run your code.
*/
require([
"globalize",
// CLDR content.
"json!cldr-data/main/en/ca-gregorian.json",
"json!cldr-data/main/en/currencies.json",
"json!cldr-data/main/en/dateFields.json",
"json!cldr-data/main/en/numbers.json",
"json!cldr-data/main/en/timeZoneNames.json",
"json!cldr-data/main/en/units.json",
"json!cldr-data/supplemental/currencyData.json",
"json!cldr-data/supplemental/likelySubtags.json",
"json!cldr-data/supplemental/metaZones.json",
"json!cldr-data/supplemental/plurals.json",
"json!cldr-data/supplemental/timeData.json",
"json!cldr-data/supplemental/weekData.json",
"json!messages/en.json",
"json!iana-tz-data.json",
// Extend Globalize with Date and Number modules.
"globalize/currency",
"globalize/date",
"globalize/message",
"globalize/number",
"globalize/plural",
"globalize/relative-time",
"globalize/unit"
], function( Globalize, enGregorian, enCurrencies, enDateFields, enNumbers,
enTimeZoneNames, enUnits, currencyData, likelySubtags, metaZones,
pluralsData, timeData, weekData, messages, ianaTzData ) {
var en, like, number;
// At this point, we have Globalize loaded. But, before we can use it, we need to feed it on the appropriate I18n content (Unicode CLDR). Read Requirements on Getting Started on the root's README.md for more information.
Globalize.load(
currencyData,
enCurrencies,
enDateFields,
enGregorian,
enNumbers,
enTimeZoneNames,
enUnits,
likelySubtags,
metaZones,
pluralsData,
timeData,
weekData
);
Globalize.loadMessages( messages );
Globalize.loadTimeZone( ianaTzData );
// Instantiate "en".
en = Globalize( "en" );
// Use Globalize to format dates.
document.getElementById( "date" ).textContent = en.formatDate( new Date(), {
datetime: "medium"
});
// Use Globalize to format dates on specific time zone.
document.getElementById( "zonedDate" ).textContent = en.formatDate( new Date(), {
datetime: "full",
timeZone: "America/Sao_Paulo"
});
// Use Globalize to format dates to parts.
document.getElementById( "dateToParts" ).innerHTML = en.formatDateToParts( new Date(), {
datetime: "medium"
}).map( function( part ) {
switch ( part.type ) {
case "month": return "<strong>" + part.value + "</strong>";
default: return part.value;
}
}).reduce( function( memo, value ) {
return memo + value;
});
// Use Globalize to format numbers.
number = en.numberFormatter();
document.getElementById( "number" ).textContent = number( 12345.6789 );
document.getElementById( "number-compact" ).textContent = en.formatNumber( 12345.6789, {
compact: "short",
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
// Use Globalize to format currencies.
document.getElementById( "currency" ).textContent = en.formatCurrency( 69900, "USD" );
// Use Globalize to get the plural form of a numeric value.
document.getElementById( "plural-number" ).textContent = number( 12345.6789 );
document.getElementById( "plural-form" ).textContent = en.plural( 12345.6789 );
// Use Globalize to format a message with plural inflection.
like = en.messageFormatter( "like" );
document.getElementById( "message-0" ).textContent = like( 0 );
document.getElementById( "message-1" ).textContent = like( 1 );
document.getElementById( "message-2" ).textContent = like( 2 );
document.getElementById( "message-3" ).textContent = like( 3 );
// Use Globalize to format a relative time.
document.getElementById( "relative-time" ).textContent = en.formatRelativeTime( -35, "second" );
// Use Globalize to format a unit.
document.getElementById( "unit" ).textContent = en.formatUnit( 60, "mile/hour", {
form: "short"
});
document.getElementById( "requirements" ).style.display = "none";
document.getElementById( "demo" ).style.display = "block";
});

View File

@@ -1,12 +0,0 @@
{
"en": {
"like": [
"{0, plural, offset:1",
" =0 {Be the first to like this}",
" =1 {You liked this}",
" one {You and someone else liked this}",
" other {You and # others liked this}",
"}"
]
}
}

View File

@@ -1,14 +0,0 @@
{
"name": "globalize-hello-world-amd-bower",
"private": true,
"comment": [
"You don't need this file. The only reasone this example does have a",
"package.json is to fool npm, so cldr-data-downloader doesn't get",
"installed on Globalize's root.",
"",
"It's analogous to `chroot .` for npm. [:P]"
],
"dependencies": {
"cldr-data-downloader": "^0.3.4"
}
}

View File

@@ -1,3 +0,0 @@
dist/
node_modules
.tmp-globalize-webpack

View File

@@ -1,74 +0,0 @@
# Globalize App example using webpack
This example demonstrates how to integrate Globalize with Webpack in your
Application. If you already have an existing Application using Webpack stack,
this example should as well provide you guidance on how to integrate Globalize.
It focuses on the [Globalize Webpack Plugin][], which automates data loading
(CLDR and app messages) during development and automates Globalize compilation
and the usage of Globalize runtime modules for production. It assumes knowledge
of Globalize, npm, and Webpack usage basics.
## Requirements
**1. Install app development dependencies**
This example uses `npm` to download the app development dependencies (i.e.,
Globalize, CLDR data, Cldrjs, Webpack, [Globalize Webpack Plugin][], and
others).
```
npm install
```
## Running the example
### Development mode
```
npm start
```
1. Start a server by running `npm start`, which uses webpack's live reload HMR
(Hot Module Replacement). See `package.json` to understand the actual shell
command that is used.
1. Point your browser at `http://localhost:8080`. Note that your browser will
automatically reload on any changes made to the application code (`app/*.js`
files). Also note that for faster page reload, formatters are created
dynamically and automatically by the [Globalize Webpack Plugin][].
1. Note you can specify the development locale of your choice by setting the
`developmentLocale` property of the Globalize Webpack Plugin on the Webpack
config file.
1. Note that CLDR data and your messages data are automatically loaded by the
[Globalize Webpack Plugin][].
1. Understand the demo by reading the source code. We have comments there for
you.
### Production mode
```
npm run build
```
1. Generate the compiled bundles by running `npm run build`, which will be
created at `./dist`. Note the production bundles are split into three chunks:
(a) vendor, which holds third-party libraries, which in this case means
Globalize Runtime modules, (b) i18n precompiled data, which means the minimum
yet sufficient set of precompiled i18n data that your application needs (one
file for each supported locale), and (c) app, which means your application code.
Also note that all the production code is already minified using UglifyJS. See
`package.json` to understand the actual shell command that is used.
1. Note that your formatters are already precompiled. This is
obvious, but worth emphasizing. It means your formatters are prebuilt, so no client
CPU clock is wasted to generate them and no CLDR or messages data needs to be
dynamically loaded. It means fast to load code (small code) and fast to run
code.
1. Point your browser at `./dist/index.html` to run the application using the
generated production files. Edit this file to display the application using a
different locale (source code has instructions).
1. Understand the demo by reading the source code. We have comments there for
you.
For more information about the plugin, see the [Globalize Webpack Plugin][]
documentation.
[Globalize Webpack Plugin]: https://github.com/rxaviers/globalize-webpack-plugin

View File

@@ -1,89 +0,0 @@
var Globalize = require( "globalize" );
var startTime = new Date();
// Standalone table.
var numberFormatter = Globalize.numberFormatter({ maximumFractionDigits: 2 });
document.getElementById( "number" ).textContent = numberFormatter( 12345.6789 );
var numberCompactFormatter = Globalize.numberFormatter({
compact: "short",
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
document.getElementById( "number-compact" ).textContent = numberCompactFormatter( 12345.6789 );
var currencyFormatter = Globalize.currencyFormatter( "USD" );
document.getElementById( "currency" ).textContent = currencyFormatter( 69900 );
var dateFormatter = Globalize.dateFormatter({ datetime: "medium" });
document.getElementById( "date" ).textContent = dateFormatter( new Date() );
var dateWithTimeZoneFormatter = Globalize.dateFormatter({
datetime: "full",
timeZone: "America/Sao_Paulo"
});
document.getElementById( "date-time-zone" ).textContent = dateWithTimeZoneFormatter( new Date() );
var _dateToPartsFormatter = Globalize.dateToPartsFormatter({ datetime: "medium" });
var dateToPartsFormatter = function( value ) {
return _dateToPartsFormatter( value, {
datetime: "medium"
}).map(function( part ) {
switch(part.type) {
case "month": return "<strong>" + part.value + "</strong>";
default: return part.value;
}
}).reduce(function( memo, value ) {
return memo + value;
});
};
document.getElementById( "date-to-parts" ).innerHTML = dateToPartsFormatter( new Date() );
var relativeTimeFormatter = Globalize.relativeTimeFormatter( "second" );
document.getElementById( "relative-time" ).textContent = relativeTimeFormatter( 0 );
var unitFormatter = Globalize.unitFormatter( "mile/hour", { form: "short" } );
document.getElementById( "unit" ).textContent = unitFormatter( 60 );
// Messages.
document.getElementById( "intro-1" ).textContent = Globalize.formatMessage( "intro-1" );
document.getElementById( "number-label" ).textContent = Globalize.formatMessage( "number-label" );
document.getElementById( "number-compact-label" ).textContent = Globalize.formatMessage( "number-compact-label" );
document.getElementById( "currency-label" ).textContent = Globalize.formatMessage( "currency-label" );
document.getElementById( "date-label" ).textContent = Globalize.formatMessage( "date-label" );
document.getElementById( "date-time-zone-label" ).textContent = Globalize.formatMessage( "date-time-zone-label" );
document.getElementById( "date-to-parts-label" ).textContent = Globalize.formatMessage( "date-to-parts-label" );
document.getElementById( "relative-time-label" ).textContent = Globalize.formatMessage( "relative-time-label" );
document.getElementById( "unit-label" ).textContent = Globalize.formatMessage( "unit-label" );
document.getElementById( "message-1" ).textContent = Globalize.formatMessage( "message-1", {
currency: currencyFormatter( 69900 ),
date: dateFormatter( new Date() ),
number: numberFormatter( 12345.6789 ),
relativeTime: relativeTimeFormatter( 0 ),
unit: unitFormatter( 60 )
});
document.getElementById( "message-2" ).textContent = Globalize.formatMessage( "message-2", {
count: 3
});
// Display demo.
document.getElementById( "requirements" ).style.display = "none";
document.getElementById( "demo" ).style.display = "block";
// Refresh elapsed time
setInterval(function() {
var elapsedTime = +( ( startTime - new Date() ) / 1000 ).toFixed( 0 );
document.getElementById( "date" ).textContent = dateFormatter( new Date() );
document.getElementById( "date-time-zone" ).textContent = dateWithTimeZoneFormatter( new Date() );
document.getElementById( "date-to-parts" ).innerHTML = dateToPartsFormatter( new Date() );
document.getElementById( "relative-time" ).textContent = relativeTimeFormatter( elapsedTime );
document.getElementById( "message-1" ).textContent = Globalize.formatMessage( "message-1", {
currency: currencyFormatter( 69900 ),
date: dateFormatter( new Date() ),
number: numberFormatter( 12345.6789 ),
relativeTime: relativeTimeFormatter( elapsedTime ),
unit: unitFormatter( 60 )
});
}, 1000);

View File

@@ -1,71 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Globalize App example using Webpack</title>
</head>
<body>
<h1>Globalize App example using Webpack</h1>
<div id="requirements">
<h2>Requirements</h2>
<ul>
<li>Read README.md for instructions on how to run the demo.
</li>
</ul>
</div>
<div id="demo" style="display: none">
<p id="intro-1">Use Globalize to internationalize your application.</p>
<table border="1" style="marginBottom: 1em;">
<tbody>
<tr>
<td><span id="number-label">Standalone Number</span></td>
<td>"<span id="number"></span>"</td>
</tr>
<tr>
<td><span id="number-compact-label">Standalone Number (compact form)</span></td>
<td>"<span id="number-compact"></span>"</td>
</tr>
<tr>
<td><span id="currency-label">Standalone Currency</span></td>
<td>"<span id="currency"></span>"</td>
</tr>
<tr>
<td><span id="date-label">Standalone Date</span></td>
<td>"<span id="date"></span>"</td>
</tr>
<tr>
<td><span id="date-time-zone-label">Standalone Date (in a specific IANA time zone, e.g., America/Sao_Paulo)</span></td>
<td>"<span id="date-time-zone"></span>"</td>
</tr>
<tr>
<td><span id="date-to-parts-label">Standalone Date (note the highlighted month, the markup was added using formatDateToParts)</span></td>
<td>"<span id="date-to-parts"></span>"</td>
</tr>
<tr>
<td><span id="relative-time-label">Standalone Relative Time</span></td>
<td>"<span id="relative-time"></span>"</td>
</tr>
<tr>
<td><span id="unit-label">Standalone Unit</span></td>
<td>"<span id="unit"></span>"</td>
</tr>
</tbody>
</table>
<p id="message-1">
An example of a message using mixed number "{number}", currency "{currency}", date "{date}", relative time "{relativeTime}", and unit "{unit}".
</p>
<p id="message-2">
An example of a message with pluralization support:
{count, plural,
one {You have one remaining task}
other {You have # remaining tasks}
}.
</p>
</div>
</body>
</html>

View File

@@ -1,25 +0,0 @@
{
"ar": {
"intro-1": "‫استخدم Globalize لتدويل تطبيقك.",
"number-label": "رقم",
"number-compact-label": "الرقم (شكل مدمج)",
"currency-label": "عملة",
"date-label": "تاريخ",
"date-time-zone-label": "التاريخ (في منطقة زمنية محددة ل إيانا، على سبيل المثال، America/Sao_Paulo)",
"date-to-parts-label": "التاريخ (لاحظ الشهر القوي، تمت إضافة الترميز باستخدام formatDateToParts)",
"relative-time-label": "الوقت النسبي",
"unit-label": "وحدة القياس",
"message-1": "مثال علي رسالة باستخدام رقم مختلط \"{number}\", عملة \"{currency}\", تاريخ \"{date}\", وقت نسبي \"{relativeTime}\", و وحدة قياس \"{unit}\" .",
"message-2": [
"مثال على رسالة بدعم صيغة الجمع:",
"{count, plural,",
" zero {لا يوجد لديك اي مهام متبقية}",
" one {لديك مهمة واحدة متبقية}",
" two {لديك اثنين من المهام المتبقية}",
" few {لديك # من المهام المتبقية}",
" many {لديك # من المهام المتبقية}",
" other {لديك # من المهام المتبقية}",
"}."
]
}
}

View File

@@ -1,21 +0,0 @@
{
"de": {
"intro-1": "Verwenden Sie Globalize um Ihre Anwendung zu internationalisieren.",
"number-label": "Zahl",
"number-compact-label": "Zahl (kompakte Form)",
"currency-label": "Währung",
"date-label": "Datum",
"date-time-zone-label": "Datum (in einer bestimmten IANA-Zeitzone, z. B. America/Sao_Paulo)",
"date-to-parts-label": "Datum (beachten Sie den hervorgehobenen Monat, das Markup wurde mit dateToPartsFormatter hinzugefügt)",
"relative-time-label": "Relative Zeit",
"unit-label": "Einheit",
"message-1": "Ein Beispiel mit Zahl \"{number}\", Währung \"{currency}\", Datum \"{date}\", relative Zeit \"{relativeTime}\", und Einheit \"{unit}\".",
"message-2": [
"Ein Beispieltext mit Unterstützung von Plural Formen: ",
"{count, plural,",
" one {Sie haben noch eine Aufgabe}",
" other {Sie haben noch # verbliebende Aufgaben}",
"}."
]
}
}

View File

@@ -1,21 +0,0 @@
{
"en": {
"intro-1": "Use Globalize to internationalize your application.",
"number-label": "Number",
"number-compact-label": "Number (compact form)",
"currency-label": "Currency",
"date-label": "Date",
"date-time-zone-label": "Date (in a specific IANA time zone, e.g., America/Sao_Paulo)",
"date-to-parts-label": "Date (note the highlighted month, the markup was added using formatDateToParts)",
"relative-time-label": "Relative Time",
"unit-label": "Unit",
"message-1": "An example of a message using mixed number \"{number}\", currency \"{currency}\", date \"{date}\", relative time \"{relativeTime}\", and unit \"{unit}\".",
"message-2": [
"An example of a message with pluralization support:",
"{count, plural,",
" one {You have one remaining task}",
" other {You have # remaining tasks}",
"}."
]
}
}

View File

@@ -1,21 +0,0 @@
{
"es": {
"intro-1": "Usa Globalize para internacionalizar tu aplicación.",
"number-label": "Número",
"number-compact-label": "Número (forma compacta)",
"currency-label": "Moneda",
"date-label": "Fecha",
"date-time-zone-label": "Fecha (en una zona horaria IANA específica, por ejemplo, America/Sao_Paulo)",
"date-to-parts-label": "Fecha (note el mes destacado en negro, el marcador de html se agregó utilizando dateToPartsFormatter)",
"relative-time-label": "Tiempo Relativo",
"unit-label": "Unidad",
"message-1": "Un ejemplo de mensaje usando números mixtos \"{number}\", monedas \"{currency}\", fechas \"{date}\", tiempo relativo \"{relativeTime}\", y unidades \"{unit}\".",
"message-2": [
"Un ejemplo de mensaje con soporte de pluralización:",
"{count, plural,",
" one {Tienes una tarea restante}",
" other {Tienes # tareas restantes}",
"}."
]
}
}

View File

@@ -1,21 +0,0 @@
{
"pt": {
"intro-1": "Use o Globalize para internacionalizar sua aplicação.",
"number-label": "Número",
"number-compact-label": "Número (forma compacta)",
"currency-label": "Moeda",
"date-label": "Data",
"date-time-zone-label": "Data (em um fuso horário IANA específico, por exemplo, America/Sao_Paulo)",
"date-to-parts-label": "Data (note o mês em negrito, a marcação HTML foi adicionada usando formatDateToParts)",
"relative-time-label": "Tempo relativo",
"unit-label": "Unit",
"message-1": "Um exemplo de mensagem com mistura de número \"{number}\", moeda \"{currency}\", data \"{date}\", tempo relativo \"{relativeTime}\", e unidade \"{unit}\".",
"message-2": [
"Um exemplo de message com suporte a pluralização:",
"{count, plural,",
" one {Você tem uma tarefa restante}",
" other {Você tem # tarefas restantes}",
"}."
]
}
}

View File

@@ -1,23 +0,0 @@
{
"ru": {
"intro-1": "Используйте Globalize для интернационализиции вашего приложения.",
"number-label": "Число",
"number-compact-label": "Число (компактная форма)",
"currency-label": "Валюта",
"date-label": "Дата",
"date-time-zone-label": "Дата (в определенном часовом поясе IANA, например, America/Sao_Paulo)",
"date-to-parts-label": "Дата (обратите внимание на сильный месяц, разметка была добавлена с помощью formatDateToParts)",
"relative-time-label": "Относительное время",
"unit-label": "Единица измерения",
"message-1": "Пример сообщения с числом \"{number}\", валютой \"{currency}\", датой \"{date}\", относительным временем \"{relativeTime}\" и единицей измерения \"{unit}\".",
"message-2": [
"Пример сообщения с поддержкой множественного числа:",
"{count, plural,",
" one {У вас осталась одна задача}",
" many {У вас осталось # задач}",
" few {У вас осталось # задачи}",
" other {У вас осталось # задачи}",
"}."
]
}
}

View File

@@ -1,20 +0,0 @@
{
"zh": {
"intro-1": "使用Globalize的国际化应用程序",
"number-label": "号码",
"number-compact-label": "编号(紧凑形式)",
"currency-label": "币",
"date-label": "迄今",
"date-time-zone-label": "日期在特定的IANA时区例如America / Sao_Paulo",
"date-to-parts-label": "日期注意强烈的月份使用formatDateToParts添加标记",
"relative-time-label": "相对时间",
"unit-label": "单元",
"message-1": "使用混合数\"{number}\",货币\"{currency}\",日期\"{date}\",相对时间\"{relativeTime}\"和单元\"{unit}\"的消息的例子。",
"message-2": [
"与多元化支持消息的例子:",
"{count, plural,",
" other {你有#剩下的任务}",
"}."
]
}
}

View File

@@ -1,17 +0,0 @@
{
"private": true,
"devDependencies": {
"cldr-data": ">=25",
"globalize": "^1.3.0",
"globalize-webpack-plugin": "^2.1.0",
"html-webpack-plugin": "^2.30.1",
"iana-tz-data": "^2017.1.0",
"webpack": "^3.11.0",
"webpack-dev-server": "^2.11.1"
},
"scripts": {
"start": "webpack-dev-server --config webpack-config.js --hot --progress --colors --inline",
"build": "NODE_ENV=production webpack --config webpack-config.js"
},
"cldr-data-urls-filter": "(core|dates|numbers|units)"
}

View File

@@ -1,63 +0,0 @@
var webpack = require( "webpack" );
var path = require("path");
var CommonsChunkPlugin = require( "webpack/lib/optimize/CommonsChunkPlugin" );
var HtmlWebpackPlugin = require( "html-webpack-plugin" );
var GlobalizePlugin = require( "globalize-webpack-plugin" );
var production = process.env.NODE_ENV === "production";
var globalizeCompiledDataRegex = new RegExp( /^(globalize\-compiled\-data)\-\S+$/ );
function subLocaleNames( name ) {
return name.replace( globalizeCompiledDataRegex, "$1" );
}
module.exports = {
entry: {
main: "./app/index.js",
},
output: {
path: path.join( __dirname, production ? "./dist" : "./tmp" ),
publicPath: production ? "" : "http://localhost:8080/",
chunkFilename: "[name].[chunkhash].js",
filename: production ? "[name].[chunkhash].js" : "app.js"
},
resolve: {
extensions: [ "*", ".js" ]
},
plugins: [
new HtmlWebpackPlugin({
template: "./index-template.html",
// filter to a single compiled globalize language
// change 'en' to language of choice or remove inject all languages
// NOTE: last language will be set language
chunks: [ "vendor", "globalize-compiled-data-en", "main" ],
chunksSortMode: function ( c1, c2 ) {
var orderedChunks = [ "vendor", "globalize-compiled-data", "main" ];
var o1 = orderedChunks.indexOf( subLocaleNames( c1.names[ 0 ]));
var o2 = orderedChunks.indexOf( subLocaleNames( c2.names[ 0 ]));
return o1 - o2;
},
}),
new GlobalizePlugin({
production: production,
developmentLocale: "en",
supportedLocales: [ "ar", "de", "en", "es", "pt", "ru", "zh" ],
messages: "messages/[locale].json",
output: "i18n/[locale].[chunkhash].js"
})
].concat( production ? [
new CommonsChunkPlugin({
name: "vendor",
minChunks: function(module) {
return (
module.context && module.context.indexOf("node_modules") !== -1
);
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
] : [] )
};

View File

@@ -1,45 +0,0 @@
# Basic Globalize Compiler example
This example focuses on the Globalize Compiler and the Globalize runtime
modules. It assumes knowledge of Globalize usage basics.
## Requirements
**1. Install Globalize dependencies and Globalize Compiler**
This example uses `npm` to download Globalize dependencies (i.e., CLDR data and
the Cldrjs library) and the [Globalize Compiler][].
```
npm install
```
[Globalize Compiler]: https://github.com/globalizejs/globalize-compiler
## Running the example
### Development mode
1. Start a server by running `python -m SimpleHTTPServer` or other alternative
servers such as [http-server][], [nginx][], [apache][].
1. Point your browser at `http://localhost:8000/development.html`. Note that the
formatters are created dynamically. Therefore, Cldrjs and CLDR data are
required.
1. Understand the demo by reading the source code. We have comments there for
you.
[http-server]: https://github.com/nodeapps/http-server
[nginx]: http://nginx.org/en/docs/
[apache]: http://httpd.apache.org/docs/trunk/
### Production mode
1. Compile the application formatters by running `npm run build`. See
`package.json` to understand the actual shell command that is used. For more
information about the compiler, see the [Globalize Compiler documentation][].
1. Point your browser at `./production.html`. Note that we don't need Cldrjs nor
CLDR data in production here.
1. Understand the demo by reading the source code. We have comments there for
you.
[Globalize Compiler documentation]: https://github.com/globalizejs/globalize-compiler#README

View File

@@ -1,58 +0,0 @@
var like, number;
// Use Globalize to format dates.
document.getElementById( "date" ).textContent = Globalize.formatDate( new Date(), {
datetime: "medium"
});
// Use Globalize to format dates on specific time zone.
document.getElementById( "zonedDate" ).textContent = Globalize.formatDate( new Date(), {
datetime: "full",
timeZone: "America/Sao_Paulo"
});
// Use Globalize to format dates to parts.
document.getElementById( "dateToParts" ).innerHTML = Globalize.formatDateToParts( new Date(), {
datetime: "medium"
}).map(function( part ) {
switch(part.type) {
case "month": return "<strong>" + part.value + "</strong>";
default: return part.value;
}
}).reduce(function( memo, value ) {
return memo + value;
});
// Use Globalize to format numbers.
number = Globalize.numberFormatter();
document.getElementById( "number" ).textContent = number( 12345.6789 );
document.getElementById( "number-compact" ).textContent = Globalize.formatNumber( 12345.6789, {
compact: "short",
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
// Use Globalize to format currencies.
document.getElementById( "currency" ).textContent = Globalize.formatCurrency( 69900, "USD" );
// Use Globalize to get the plural form of a numeric value.
document.getElementById( "plural-number" ).textContent = number( 12345.6789 );
document.getElementById( "plural-form" ).textContent = Globalize.plural( 12345.6789 );
// Use Globalize to format a message with plural inflection.
like = Globalize.messageFormatter( "like" );
document.getElementById( "message-0" ).textContent = like( 0 );
document.getElementById( "message-1" ).textContent = like( 1 );
document.getElementById( "message-2" ).textContent = like( 2 );
document.getElementById( "message-3" ).textContent = like( 3 );
// Use Globalize to format a relative time.
document.getElementById( "relative-time" ).textContent = Globalize.formatRelativeTime( -35, "second" );
// Use Globalize to format a unit.
document.getElementById( "unit" ).textContent = Globalize.formatUnit( 60, "mile/hour", {
form: "short"
});
document.getElementById( "requirements" ).style.display = "none";
document.getElementById( "demo" ).style.display = "block";

View File

@@ -1,121 +0,0 @@
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Basic Globalize Compiler example (development mode)</title>
</head>
<body>
<h1>Basic Globalize Compiler example (development mode)</h1>
<div id="requirements">
<h2>Requirements</h2>
<ul>
<li>Read README.md for instructions.</li>
</ul>
</div>
<div id="demo" style="display: none">
<h2>Demo output</h2>
<p>Now: <span id="date"></span></p>
<p>Now: <span id="dateToParts"></span> (note the highlighted month, the markup was added using formatDateToParts)</p>
<p>Now (in America/Sao_Paulo): <span id="zonedDate"></span></p>
<p>A number: <span id="number"></span></p>
<p>A number (compact form): <span id="number-compact"></span></p>
<p>A currency: <span id="currency"></span></p>
<p>Plural form of <span id="plural-number"></span> is <span id="plural-form"></span></p>
<p>Messages:</p>
<ul>
<li><span id="message-0"></span></li>
<li><span id="message-1"></span></li>
<li><span id="message-2"></span></li>
<li><span id="message-3"></span></li>
</ul>
<p>Something happened: <span id="relative-time"></span></p>
<p>Speed limit: <span id="unit"></span></p>
</div>
<!--
First, we load Globalize's dependencies (`cldrjs` and its supplemental
module).
-->
<script src="node_modules/globalize/node_modules/cldrjs/dist/cldr.js"></script>
<script src="node_modules/globalize/node_modules/cldrjs/dist/cldr/event.js"></script>
<script src="node_modules/globalize/node_modules/cldrjs/dist/cldr/supplemental.js"></script>
<!--
npm@3 installs flat by default differently from npm@1 and npm@2, so either
the below or the above will work. Don't do this at your application, pick
one.
-->
<script src="node_modules/cldrjs/dist/cldr.js"></script>
<script src="node_modules/cldrjs/dist/cldr/event.js"></script>
<script src="node_modules/cldrjs/dist/cldr/supplemental.js"></script>
<!--
Next, we load Globalize and its modules. Note they are already available on
this repository. If it's not, read Usage on Getting Started on the root's
README.md.
-->
<script src="node_modules/globalize/dist/globalize.js"></script>
<script src="node_modules/globalize/dist/globalize/message.js"></script>
<script src="node_modules/globalize/dist/globalize/number.js"></script>
<script src="node_modules/globalize/dist/globalize/plural.js"></script>
<!-- Load after globalize/number.js -->
<script src="node_modules/globalize/dist/globalize/date.js"></script>
<script src="node_modules/globalize/dist/globalize/currency.js"></script>
<!-- Load after globalize/number.js and globalize/plural.js-->
<script src="node_modules/globalize/dist/globalize/relative-time.js"></script>
<script src="node_modules/globalize/dist/globalize/unit.js"></script>
<!-- Load jQuery to fetch the CLDR and message JSONs -->
<script src="node_modules/jquery/dist/jquery.js"></script>
<script>
// At this point, we have Globalize loaded. But, before we can use it, we
// need to feed it on the appropriate I18n content (Unicode CLDR). In order
// to do so, we use `Globalize.load()` and pass the content. On this demo,
// we made the things a little easier for you: we've embedded static JSON
// into the demo. So, you don't need to actually fetch it elsewhere.
$.when(
$.getJSON( "node_modules/cldr-data/main/en/ca-gregorian.json" ),
$.getJSON( "node_modules/cldr-data/main/en/currencies.json" ),
$.getJSON( "node_modules/cldr-data/main/en/dateFields.json" ),
$.getJSON( "node_modules/cldr-data/main/en/numbers.json" ),
$.getJSON( "node_modules/cldr-data/main/en/timeZoneNames.json" ),
$.getJSON( "node_modules/cldr-data/main/en/units.json" ),
$.getJSON( "node_modules/cldr-data/supplemental/currencyData.json" ),
$.getJSON( "node_modules/cldr-data/supplemental/likelySubtags.json" ),
$.getJSON( "node_modules/cldr-data/supplemental/metaZones.json" ),
$.getJSON( "node_modules/cldr-data/supplemental/plurals.json" ),
$.getJSON( "node_modules/cldr-data/supplemental/timeData.json" ),
$.getJSON( "node_modules/cldr-data/supplemental/weekData.json" ),
$.getJSON( "messages.json" ),
$.getJSON( "node_modules/iana-tz-data/iana-tz-data.json" )
).then(function( enCaGregorian, enCurrencies, enDateFields, enNumbers, enTimeZoneNames, enUnits,
currencyData, likelySubtags, metaZones, plurals, timeData, weekData, messages, ianaTzData ) {
Globalize.load( enCaGregorian[ 0 ] );
Globalize.load( enCurrencies[ 0 ] );
Globalize.load( enDateFields[ 0 ] );
Globalize.load( enNumbers[ 0 ] );
Globalize.load( enTimeZoneNames[ 0 ] );
Globalize.load( enUnits[ 0 ] );
Globalize.load( currencyData[ 0 ] );
Globalize.load( likelySubtags[ 0 ] );
Globalize.load( metaZones[ 0 ] );
Globalize.load( plurals[ 0 ] );
Globalize.load( timeData[ 0 ] );
Globalize.load( weekData[ 0 ] );
Globalize.loadMessages( messages[ 0 ] );
Globalize.loadTimeZone( ianaTzData[ 0 ] );
Globalize.locale("en");
// Load and execute our App.
$.getScript( "app.js" );
})
</script>
</body>
</html>

View File

@@ -1,12 +0,0 @@
{
"en": {
"like": [
"{0, plural, offset:1",
" =0 {Be the first to like this}",
" =1 {You liked this}",
" one {You and someone else liked this}",
" other {You and # others liked this}",
"}"
]
}
}

View File

@@ -1,15 +0,0 @@
{
"name": "basic-globalize-compiler",
"private": true,
"scripts": {
"build": "globalize-compiler -l en -m messages.json -o compiled-formatters.js app.js"
},
"devDependencies": {
"cldr-data": ">=25",
"globalize": "^1.5.0",
"globalize-compiler": "^1.1.1",
"iana-tz-data": "^2017.1.0",
"jquery": "latest"
},
"cldr-data-urls-filter": "(core|dates|numbers|units)"
}

View File

@@ -1,75 +0,0 @@
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Basic Globalize Compiler example (production mode)</title>
</head>
<body>
<h1>Basic Globalize Compiler example (production mode)</h1>
<div id="requirements">
<h2>Requirements</h2>
<ul>
<li>You need to build the `compiled-formatters.js`. Read README.md for instructions.
</li>
</ul>
</div>
<div id="demo" style="display: none">
<h2>Demo output</h2>
<p>Now: <span id="date"></span></p>
<p>Now: <span id="dateToParts"></span> (note the highlighted month, the markup was added using formatDateToParts)</p>
<p>Now (in America/Sao_Paulo): <span id="zonedDate"></span></p>
<p>A number: <span id="number"></span></p>
<p>A number (compact form): <span id="number-compact"></span></p>
<p>A currency: <span id="currency"></span></p>
<p>Plural form of <span id="plural-number"></span> is <span id="plural-form"></span></p>
<p>Messages:</p>
<ul>
<li><span id="message-0"></span></li>
<li><span id="message-1"></span></li>
<li><span id="message-2"></span></li>
<li><span id="message-3"></span></li>
</ul>
<p>Something happened: <span id="relative-time"></span></p>
<p>Speed limit: <span id="unit"></span></p>
</div>
<!--
Note, we don't need cldrjs library anymore because the formatters have
already been created by the compilation step. More info below.
-->
<!-- Load Globalize runtime and its runtime modules -->
<script src="node_modules/globalize/dist/globalize-runtime.js"></script>
<script src="node_modules/globalize/dist/globalize-runtime/message.js"></script>
<script src="node_modules/globalize/dist/globalize-runtime/number.js"></script>
<script src="node_modules/globalize/dist/globalize-runtime/plural.js"></script>
<!-- Load after globalize-runtime/number.js -->
<script src="node_modules/globalize/dist/globalize-runtime/date.js"></script>
<script src="node_modules/globalize/dist/globalize-runtime/currency.js"></script>
<!--
Load after globalize-runtime/number.js and globalize-runtime/plural.js
-->
<script src="node_modules/globalize/dist/globalize-runtime/relative-time.js"></script>
<script src="node_modules/globalize/dist/globalize-runtime/unit.js"></script>
<!--
Then, load the compiled formatters.
Note, we don't need to feed Globalize on CLDR data anymore because the
formatters have already been created by the compilation step and their
"snapshots" are available below.
-->
<script src="compiled-formatters.js"></script>
<!-- Our App -->
<script>
Globalize.locale("en");
</script>
<script src="app.js"></script>
</body>
</html>

View File

@@ -1,57 +0,0 @@
# Hello World (Node.js + npm)
We assume you know what [Node.js](http://nodejs.org/) and
[npm](https://www.npmjs.org/) is.
The demo contains one single file:
```
.
└── main.js
```
Before running it, execute the requirements below.
## Requirements
**1. Install Globalize**
Let's use npm to download Globalize. For more information on regard of
installation, please read [Getting Started](../../README.md#installation).
```
npm install
```
Then, you'll get this:
```
.
├── node_modules/
│ ├── globalize/
│ │ └── dist/
│ │ ├── globalize
│ │ │ ├── date.js
│ │ │ └── ...
│ │ └── globalize.js
│ └── ...
└── main.js
```
**2. Dependencies**
No action needed, because npm has already handled that for us.
**3. CLDR content**
No action needed, because npm has already handled that for us. For more
information, see [npm's cldr-data](https://github.com/rxaviers/cldr-data-npm).
## Running the demo
Once you've completed the requirements above:
1. Run `node main.js`.
1. Understand the demo by reading the source code. We have comments there for you.

View File

@@ -1,65 +0,0 @@
var like;
var Globalize = require( "globalize" );
// Before we can use Globalize, we need to feed it on the appropriate I18n content (Unicode CLDR). Read Requirements on Getting Started on the root's README.md for more information.
Globalize.load(
require( "cldr-data/main/en/ca-gregorian" ),
require( "cldr-data/main/en/currencies" ),
require( "cldr-data/main/en/dateFields" ),
require( "cldr-data/main/en/numbers" ),
require( "cldr-data/main/en/timeZoneNames" ),
require( "cldr-data/main/en/units" ),
require( "cldr-data/supplemental/currencyData" ),
require( "cldr-data/supplemental/likelySubtags" ),
require( "cldr-data/supplemental/metaZones" ),
require( "cldr-data/supplemental/plurals" ),
require( "cldr-data/supplemental/timeData" ),
require( "cldr-data/supplemental/weekData" )
);
Globalize.loadMessages( require( "./messages/en" ) );
Globalize.loadTimeZone( require( "iana-tz-data" ) );
// Set "en" as our default locale.
Globalize.locale( "en" );
// Use Globalize to format dates.
console.log( Globalize.formatDate( new Date(), { datetime: "medium" } ) );
// Use Globalize to format dates in specific time zones.
console.log( Globalize.formatDate( new Date(), {
datetime: "full",
timeZone: "America/Sao_Paulo"
}));
// Use Globalize to format dates to parts.
console.log( Globalize.formatDateToParts( new Date(), { datetime: "medium" } ) );
// Use Globalize to format numbers.
console.log( Globalize.formatNumber( 12345.6789 ) );
// Use Globalize to format numbers (compact form).
console.log( Globalize.formatNumber( 12345.6789, {
compact: "short",
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
}));
// Use Globalize to format currencies.
console.log( Globalize.formatCurrency( 69900, "USD" ) );
// Use Globalize to get the plural form of a numeric value.
console.log( Globalize.plural( 12345.6789 ) );
// Use Globalize to format a message with plural inflection.
like = Globalize.messageFormatter( "like" );
console.log( like( 0 ) );
console.log( like( 1 ) );
console.log( like( 2 ) );
console.log( like( 3 ) );
// Use Globalize to format relative time.
console.log( Globalize.formatRelativeTime( -35, "second" ) );
// Use Globalize to format unit.
console.log( Globalize.formatUnit( 60, "mile/hour", { form: "short" } ) );

View File

@@ -1,12 +0,0 @@
{
"en": {
"like": [
"{0, plural, offset:1",
" =0 {Be the first to like this}",
" =1 {You liked this}",
" one {You and someone else liked this}",
" other {You and # others liked this}",
"}"
]
}
}

View File

@@ -1,10 +0,0 @@
{
"name": "globalize-hello-world-node-npm",
"private": true,
"dependencies": {
"cldr-data": "latest",
"globalize": "^1.3.0",
"iana-tz-data": ">=2017.0.0"
},
"cldr-data-urls-filter": "(core|dates|numbers|units)"
}

View File

@@ -1,81 +0,0 @@
# Hello World (plain javascript)
The demo contains one single file:
```
.
└── index.html
```
Before running it, execute the requirements below.
## Requirements
**1. Dependencies**
The demo requires Globalize and its dependencies. Globalize's dependencies are listed on [Getting
Started](../../README.md#dependencies), and the only one is
[cldrjs](https://github.com/rxaviers/cldrjs). You are free to fetch it the way you want. But, as an
exercise of this demo, we'll download it ourselves. So:
1. Click at [Globalize releases tab](https://github.com/globalizejs/globalize/releases).
1. Download the latest package.
1. Unzip it.
1. Rename the extracted directory `globalize` and move it alongside `index.html` and `README.md`.
1. Click at [cldrjs releases tab](https://github.com/rxaviers/cldrjs/releases).
1. Download the latest package.
1. Unzip it.
1. Rename the extracted directory `cldrjs` and move it alongside `index.html` and `README.md`.
Then, you'll get this:
```
.
├── cldrjs
│ └── dist
│ ├── cldr.js
│ ├── ...
│ └── cldr
│ ├── event.js
│ ├── supplemental.js
│ └── ...
├── globalize
│ └── dist
│ ├── globalize.js
│ ├── ...
│ └── globalize
│ ├── currency.js
│ ├── date.js
│ └── ...
├── index.html
└── README.md
```
For more information read [cldrjs' usage and
installation](https://github.com/rxaviers/cldrjs#usage-and-installation) docs.
**2. CLDR content**
Another typical Globalize requirement is to fetch CLDR content yourself. But, on
this demo we made the things a little easier for you: we've embedded static JSON
into the demo. So, you don't need to actually fetch it anywhere. For more
information about fetching Unicode CLDR JSON data, see [How do I get CLDR
data?](../../doc/cldr.md).
No action needed here.
**3. Globalize `dist` files**
*This step only applies if you are building the source files. If you have downloaded a ZIP or a TAR.GZ or are using a package manager (such as bower or npm) to install then you can ignore this step.*
[Install the development external dependencies](../../README.md#install-development-external-dependencies) and [build the distribution files](../../README.md#build).
## Running the demo
Once you've completed the requirements above:
1. Point your browser at `./index.html`.
1. Open your JavaScript console to see the demo output.
1. Understand the demo by reading the source code. We have comments there for
you.

View File

@@ -1,445 +0,0 @@
<!doctype html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Globalize Hello World (plain javascript)</title>
</head>
<body>
<h1>Globalize Hello World (plain javascript)</h1>
<div id="requirements">
<h2>Requirements</h2>
<ul>
<li>You need to download `cldrjs` and `globalize` dependencies yourself. Read README.md for instructions.
</li>
</ul>
</div>
<div id="demo" style="display: none">
<h2>Demo output</h2>
<p>Now: <span id="date"></span></p>
<p>Now: <span id="dateToParts"></span> (note the highlighted month, the markup was added using formatDateToParts)</p>
<p>Now (in America/Sao_Paulo): <span id="zonedDate"></span></p>
<p>A number: <span id="number"></span></p>
<p>A number (compact form): <span id="number-compact"></span></p>
<p>A currency: <span id="currency"></span></p>
<p>Plural form of <span id="plural-number"></span> is <span id="plural-form"></span></p>
<p>Messages:</p>
<ul>
<li><span id="message-0"></span></li>
<li><span id="message-1"></span></li>
<li><span id="message-2"></span></li>
<li><span id="message-3"></span></li>
</ul>
<p>Something happened: <span id="relative-time"></span></p>
<p>Speed limit: <span id="unit"></span></p>
</div>
<!--
First, we load Globalize's dependencies (`cldrjs` and its supplemental
module).
-->
<script src="cldrjs/dist/cldr.js"></script>
<script src="cldrjs/dist/cldr/event.js"></script>
<script src="cldrjs/dist/cldr/supplemental.js"></script>
<!--
Next, we load Globalize and its modules. Note they are already available on
this repository. If it's not, read Usage on Getting Started on the root's
README.md.
-->
<script src="globalize/dist/globalize.js"></script>
<script src="globalize/dist/globalize/message.js"></script>
<script src="globalize/dist/globalize/number.js"></script>
<script src="globalize/dist/globalize/plural.js"></script>
<!-- Load after globalize/number.js -->
<script src="globalize/dist/globalize/date.js"></script>
<script src="globalize/dist/globalize/currency.js"></script>
<!-- Load after globalize/number.js and globalize/plural.js-->
<script src="globalize/dist/globalize/relative-time.js"></script>
<script src="globalize/dist/globalize/unit.js"></script>
<script>
// At this point, we have Globalize loaded. But, before we can use it, we
// need to feed it on the appropriate I18n content (Unicode CLDR). In order
// to do so, we use `Globalize.load()` and pass the content. On this demo,
// we made the things a little easier for you: we've embedded static JSON
// into the demo. So, you don't need to actually fetch it elsewhere.
Globalize.load({
"main": {
"en": {
"identity": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"generation": {
"_date": "$Date: 2014-03-13 22:27:12 -0500 (Thu, 13 Mar 2014) $"
},
"language": "en"
},
"dates": {
"calendars": {
"gregorian": {
"days": {
"format": {
"wide": {
"sun": "Sunday",
"mon": "Monday",
"tue": "Tuesday",
"wed": "Wednesday",
"thu": "Thursday",
"fri": "Friday",
"sat": "Saturday"
}
}
},
"months": {
"format": {
"abbreviated": {
"1": "Jan",
"2": "Feb",
"3": "Mar",
"4": "Apr",
"5": "May",
"6": "Jun",
"7": "Jul",
"8": "Aug",
"9": "Sep",
"10": "Oct",
"11": "Nov",
"12": "Dec"
},
"wide": {
"1": "January",
"2": "February",
"3": "March",
"4": "April",
"5": "May",
"6": "June",
"7": "July",
"8": "August",
"9": "September",
"10": "October",
"11": "November",
"12": "December"
}
}
},
"dayPeriods": {
"format": {
"wide": {
"am": "AM",
"am-alt-variant": "am",
"noon": "noon",
"pm": "PM",
"pm-alt-variant": "pm"
}
}
},
"dateFormats": {
"full": "EEEE, MMMM d, y",
"medium": "MMM d, y"
},
"timeFormats": {
"full": "h:mm:ss a zzzz",
"medium": "h:mm:ss a",
},
"dateTimeFormats": {
"full": "{1} 'at' {0}",
"medium": "{1}, {0}"
}
}
},
"fields": {
"second": {
"displayName": "Second",
"relative-type-0": "now",
"relativeTime-type-future": {
"relativeTimePattern-count-one": "in {0} second",
"relativeTimePattern-count-other": "in {0} seconds"
},
"relativeTime-type-past": {
"relativeTimePattern-count-one": "{0} second ago",
"relativeTimePattern-count-other": "{0} seconds ago"
}
}
},
"timeZoneNames": {
"metazone": {
"Brasilia": {
"long": {
"generic": "Brasilia Time",
"standard": "Brasilia Standard Time",
"daylight": "Brasilia Summer Time"
}
}
}
}
},
"numbers": {
"currencies": {
"USD": {
"symbol": "$"
}
},
"defaultNumberingSystem": "latn",
"symbols-numberSystem-latn": {
"decimal": ".",
"exponential": "E",
"group": ",",
"infinity": "∞",
"minusSign": "-",
"nan": "NaN",
"percentSign": "%",
"perMille": "‰",
"plusSign": "+",
"timeSeparator": ":"
},
"decimalFormats-numberSystem-latn": {
"standard": "#,##0.###",
"short": {
"decimalFormat": {
"1000-count-one": "0K",
"1000-count-other": "0K",
"10000-count-one": "00K",
"10000-count-other": "00K",
"100000-count-one": "000K",
"100000-count-other": "000K",
"1000000-count-one": "0M",
"1000000-count-other": "0M",
"10000000-count-one": "00M",
"10000000-count-other": "00M",
"100000000-count-one": "000M",
"100000000-count-other": "000M",
"1000000000-count-one": "0B",
"1000000000-count-other": "0B",
"10000000000-count-one": "00B",
"10000000000-count-other": "00B",
"100000000000-count-one": "000B",
"100000000000-count-other": "000B",
"1000000000000-count-one": "0T",
"1000000000000-count-other": "0T",
"10000000000000-count-one": "00T",
"10000000000000-count-other": "00T",
"100000000000000-count-one": "000T",
"100000000000000-count-other": "000T"
}
}
},
"currencyFormats-numberSystem-latn": {
"currencySpacing": {
"beforeCurrency": {
"currencyMatch": "[:^S:]",
"surroundingMatch": "[:digit:]",
"insertBetween": " "
},
"afterCurrency": {
"currencyMatch": "[:^S:]",
"surroundingMatch": "[:digit:]",
"insertBetween": " "
}
},
"standard": "¤#,##0.00"
}
},
"units": {
"short": {
"per": {
"compoundUnitPattern": "{0}/{1}"
},
"speed-mile-per-hour": {
"displayName": "miles/hour",
"unitPattern-count-one": "{0} mph",
"unitPattern-count-other": "{0} mph"
}
}
}
}
},
"supplemental": {
"version": {
"_cldrVersion": "25",
"_number": "$Revision: 91 $"
},
"currencyData": {
"fractions": {
"DEFAULT": {
"_rounding": "0",
"_digits": "2"
}
}
},
"likelySubtags": {
"en": "en-Latn-US",
},
"metaZones": {
"metazoneInfo": {
"timezone": {
"America": {
"Sao_Paulo": [
{
"usesMetazone": {
"_mzone": "Brasilia"
}
}
]
}
}
}
},
"plurals-type-cardinal": {
"en": {
"pluralRule-count-one": "i = 1 and v = 0 @integer 1",
"pluralRule-count-other": " @integer 0, 2~16, 100, 1000, 10000, 100000, 1000000, … @decimal 0.0~1.5, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0, …"
}
}
}
});
Globalize.loadMessages({
"en": {
"like": [
"{0, plural, offset:1",
" =0 {Be the first to like this}",
" =1 {You liked this}",
" one {You and someone else liked this}",
" other {You and # others liked this}",
"}"
]
}
});
Globalize.loadTimeZone({
"zoneData": {
"America": {
"Sao_Paulo": {
"abbrs": [
"LMT", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03",
"-02", "-03", "-02", "-03", "-02", "-03", "-02", "-03", "-02"
],
"untils": [
-1767214412000, -1206957600000, -1191362400000, -1175374800000, -1159826400000,
-633819600000, -622069200000, -602283600000, -591832800000, -570747600000,
-560210400000, -539125200000, -531352800000, -195426000000, -184197600000,
-155163600000, -150069600000, -128898000000, -121125600000, -99954000000, -89589600000,
-68418000000, -57967200000, 499748400000, 511236000000, 530593200000, 540266400000,
562129200000, 571197600000, 592974000000, 602042400000, 624423600000, 634701600000,
656478000000, 666756000000, 687927600000, 697600800000, 719982000000, 728445600000,
750826800000, 761709600000, 782276400000, 793159200000, 813726000000, 824004000000,
844570800000, 856058400000, 876106800000, 888717600000, 908074800000, 919562400000,
938919600000, 951616800000, 970974000000, 982461600000, 1003028400000, 1013911200000,
1036292400000, 1045360800000, 1066532400000, 1076810400000, 1099364400000,
1108864800000, 1129431600000, 1140314400000, 1162695600000, 1172368800000,
1192330800000, 1203213600000, 1224385200000, 1234663200000, 1255834800000,
1266717600000, 1287284400000, 1298167200000, 1318734000000, 1330221600000,
1350788400000, 1361066400000, 1382238000000, 1392516000000, 1413687600000,
1424570400000, 1445137200000, 1456020000000, 1476586800000, 1487469600000,
1508036400000, 1518919200000, 1540090800000, 1550368800000, 1571540400000,
1581818400000, 1602990000000, 1613872800000, 1634439600000, 1645322400000,
1665889200000, 1677376800000, 1697338800000, 1708221600000, 1729393200000,
1739671200000, 1760842800000, 1771725600000, 1792292400000, 1803175200000,
1823742000000, 1834624800000, 1855191600000, 1866074400000, 1887246000000,
1897524000000, 1918695600000, 1928973600000, 1950145200000, 1960423200000,
1981594800000, 1992477600000, 2013044400000, 2024532000000, 2044494000000,
2055376800000, 2076548400000, 2086826400000, 2107998000000, 2118880800000,
2139447600000, null
],
"offsets": [
186.4667, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180,
120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120,
180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180,
120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120,
180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180,
120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120,
180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120, 180,
120, 180, 120, 180, 120, 180, 120, 180, 120, 180, 120
],
"isdsts": [
0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0,
1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1
]
}
}
}
});
var en, like, number;
// Instantiate "en".
en = Globalize( "en" );
// Use Globalize to format dates.
document.getElementById( "date" ).textContent = en.formatDate( new Date(), {
datetime: "medium"
});
// Use Globalize to format dates on specific time zone.
document.getElementById( "zonedDate" ).textContent = en.formatDate( new Date(), {
datetime: "full",
timeZone: "America/Sao_Paulo"
});
// Use Globalize to format dates to parts.
document.getElementById( "dateToParts" ).innerHTML = en.formatDateToParts( new Date(), {
datetime: "medium"
}).map(function( part ) {
switch(part.type) {
case "month": return "<strong>" + part.value + "<\/strong>";
default: return part.value;
}
}).reduce(function( memo, value ) {
return memo + value;
});
// Use Globalize to format numbers.
number = en.numberFormatter();
document.getElementById( "number" ).textContent = number( 12345.6789 );
document.getElementById( "number-compact" ).textContent = en.formatNumber( 12345.6789, {
compact: "short",
minimumSignificantDigits: 1,
maximumSignificantDigits: 3
});
// Use Globalize to format currencies.
document.getElementById( "currency" ).textContent = en.formatCurrency( 69900, "USD" );
// Use Globalize to get the plural form of a numeric value.
document.getElementById( "plural-number" ).textContent = number( 12345.6789 );
document.getElementById( "plural-form" ).textContent = en.plural( 12345.6789 );
// Use Globalize to format a message with plural inflection.
like = en.messageFormatter( "like" );
document.getElementById( "message-0" ).textContent = like( 0 );
document.getElementById( "message-1" ).textContent = like( 1 );
document.getElementById( "message-2" ).textContent = like( 2 );
document.getElementById( "message-3" ).textContent = like( 3 );
// Use Globalize to format a relative time.
document.getElementById( "relative-time" ).textContent = en.formatRelativeTime( -35, "second" );
// Use Globalize to format a unit.
document.getElementById( "unit" ).textContent = en.formatUnit( 60, "mile/hour", {
form: "short"
});
document.getElementById( "requirements" ).style.display = "none";
document.getElementById( "demo" ).style.display = "block";
</script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@@ -1,109 +0,0 @@
{
"name": "globalize",
"version": "1.7.0",
"description": "A JavaScript library for internationalization and localization that leverages the official Unicode CLDR JSON data.",
"keywords": [
"utility",
"globalization",
"internationalization",
"multilingualization",
"localization",
"g11n",
"i18n",
"m17n",
"L10n",
"localize",
"format",
"parse",
"translate",
"strings",
"numbers",
"dates",
"times",
"calendars",
"plural",
"plurals",
"pluralize",
"cultures",
"languages",
"locales",
"Unicode",
"CLDR",
"JSON"
],
"homepage": "https://github.com/globalizejs/globalize",
"author": {
"name": "OpenJS Foundation and other contributors",
"url": "https://github.com/globalizejs/globalize/blob/master/AUTHORS.txt"
},
"maintainers": [
{
"name": "Jörn Zaefferer",
"email": "joern.zaefferer@gmail.com",
"url": "http://bassistance.de"
},
{
"name": "Rafael Xavier de Souza",
"email": "rxaviers@gmail.com",
"url": "http://rafael.xavier.blog.br"
}
],
"main": "./dist/node-main.js",
"files": [
"CONTRIBUTING.md",
"dist/",
"!dist/.build",
"doc/",
"examples/",
"!examples/**/.tmp-globalize-webpack",
"!examples/**/bower_components",
"!examples/**/node_modules",
"!examples/plain-javascript/cldrjs",
"!examples/plain-javascript/globalize",
"README.md"
],
"repository": {
"type": "git",
"url": "git://github.com/globalizejs/globalize.git"
},
"bugs": {
"url": "https://github.com/globalizejs/globalize/issues"
},
"dependencies": {
"cldrjs": "^0.5.4"
},
"devDependencies": {
"cldr-data-downloader": "^0.3.1",
"eslint-config-jquery": "3.0.0",
"glob": "^7.1.2",
"globalize-compiler": "^1.1.1",
"grunt": "1.2.0",
"grunt-check-dependencies": "1.0.0",
"grunt-commitplease": "0.0.6",
"grunt-compare-size": "0.4.2",
"grunt-contrib-clean": "1.1.0",
"grunt-contrib-connect": "0.8.0",
"grunt-contrib-copy": "1.0.0",
"grunt-contrib-qunit": "2.0.0",
"grunt-contrib-requirejs": "1.0.0",
"grunt-contrib-uglify": "3.0.1",
"grunt-contrib-watch": "1.0.0",
"grunt-eslint": "23.0.0",
"grunt-git-authors": "^3.2.0",
"grunt-mocha-test": "^0.13.2",
"gzip-js": "0.3.2",
"iana-tz-data": ">=2017.0.0",
"matchdep": "1.0.1",
"mocha": "^3.4.2",
"qunit": "2.12.0",
"semver": "^5.3.0",
"zoned-date-time": "1.1.0"
},
"commitplease": {
"nohook": true
},
"license": "MIT",
"scripts": {
"test": "grunt"
}
}

View File

@@ -1,7 +0,0 @@
var packageJson = require( "../../package.json" );
var semver = require( "semver" );
// Note argv[0] is supposed to be `node`, argv[1] to be this file.
var next = process.argv[ 2 ];
var prereleaseIdentifier = process.argv[ 3 ];
console.log( semver.inc( packageJson.version, next, prereleaseIdentifier ) );

View File

@@ -1,11 +0,0 @@
var fs = require( "fs" );
var packageJson = require( "../../package.json" );
var path = require( "path" );
// Note argv[0] is supposed to be `node`, argv[1] to be this file.
packageJson.version = process.argv[ 2 ];
fs.writeFileSync(
path.join( __dirname, "../../package.json" ),
JSON.stringify( packageJson, null, 2 ) + "\n"
);

Some files were not shown because too many files have changed in this diff Show More