Skip to content

Commit e5c0da0

Browse files
committed
feat(input) add support to for week
Add support to date filter for outputing week of year Partially closes angular#757
1 parent 9cc6b73 commit e5c0da0

File tree

4 files changed

+311
-3
lines changed

4 files changed

+311
-3
lines changed

src/ng/directive/input.js

+181
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/;
1313
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
1414
var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
1515
var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)$/;
16+
var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
1617

1718
var inputType = {
1819

@@ -222,6 +223,73 @@ var inputType = {
222223
</doc:example>
223224
*/
224225
'datetime-local': dateTimeLocalInputType,
226+
227+
/**
228+
* @ngdoc inputType
229+
* @name ng.directive:input.week
230+
*
231+
* @description
232+
* HTML5 or text input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
233+
* the HTML5 week input, a text element will be used. The text must be entered in a valid ISO-8601
234+
* week format (yyyy-W##), for example: `2013-W02`. Will also accept a valid ISO
235+
* week string or Date object as model input, but will always output a Date object to the model.
236+
*
237+
* @param {string} ngModel Assignable angular expression to data-bind to.
238+
* @param {string=} name Property name of the form under which the control is published.
239+
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
240+
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
241+
* @param {string=} required Sets `required` validation error key if the value is not entered.
242+
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
243+
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
244+
* `required` when you want to data-bind to the `required` attribute.
245+
* @param {string=} ngChange Angular expression to be executed when input changes due to user
246+
* interaction with the input element.
247+
*
248+
* @example
249+
<doc:example>
250+
<doc:source>
251+
<script>
252+
function Ctrl($scope) {
253+
$scope.value = '2013-W01';
254+
}
255+
</script>
256+
<form name="myForm" ng-controller="Ctrl as dateCtrl">
257+
Pick a date between in 2013:
258+
<input type="date" name="input" ng-model="value"
259+
placeholder="yyyy-MM-dd" min="2012-W32" max="2013-W52" required />
260+
<span class="error" ng-show="myForm.input.$error.required">
261+
Required!</span>
262+
<span class="error" ng-show="myForm.input.$error.week">
263+
Not a valid date!</span>
264+
<tt>value = {{value}}</tt><br/>
265+
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
266+
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
267+
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
268+
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
269+
</form>
270+
</doc:source>
271+
<doc:scenario>
272+
it('should initialize to model', function() {
273+
expect(binding('value')).toEqual('2013-W01');
274+
expect(binding('myForm.input.$valid')).toEqual('true');
275+
});
276+
277+
it('should be invalid if empty', function() {
278+
input('value').enter('');
279+
expect(binding('value')).toEqual('');
280+
expect(binding('myForm.input.$valid')).toEqual('false');
281+
});
282+
283+
it('should be invalid if over max', function() {
284+
input('value').enter('2015-W01');
285+
expect(binding('value')).toEqual('');
286+
expect(binding('myForm.input.$valid')).toEqual('false');
287+
});
288+
</doc:scenario>
289+
</doc:example>
290+
*/
291+
'week': weekInputType,
292+
225293
/**
226294
* @ngdoc inputType
227295
* @name ng.directive:input.number
@@ -662,6 +730,119 @@ function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
662730
}
663731
}
664732

733+
734+
function weekInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
735+
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
736+
737+
ctrl.$parsers.push(function(value) {
738+
if(ctrl.$isEmpty(value)) {
739+
ctrl.$setValidity('week', true);
740+
return value;
741+
}
742+
743+
if(WEEK_REGEXP.test(value)) {
744+
ctrl.$setValidity('week', true);
745+
return new Date(getTime(value).time);
746+
}
747+
748+
ctrl.$setValidity('week', false);
749+
return undefined;
750+
});
751+
752+
ctrl.$formatters.push(function(value) {
753+
if(isDate(value)) {
754+
return $filter('date')(value, 'yyyy-Www');
755+
}
756+
return ctrl.$isEmpty(value) ? '' : ''+value;
757+
});
758+
759+
if(attr.min) {
760+
var minValidator = function(value) {
761+
var valTime = getTime(value),
762+
minTime = getTime(attr.min);
763+
764+
var valid = ctrl.$isEmpty(value) ||
765+
valTime.time >= minTime.time;
766+
767+
ctrl.$setValidity('min', valid);
768+
return valid ? value : undefined;
769+
};
770+
771+
ctrl.$parsers.push(minValidator);
772+
ctrl.$formatters.push(minValidator);
773+
}
774+
775+
if(attr.max) {
776+
var maxValidator = function(value) {
777+
debugger;
778+
var valTime = getTime(value),
779+
maxTime = getTime(attr.max);
780+
781+
var valid = ctrl.$isEmpty(value) ||
782+
valTime.time <= maxTime.time;
783+
784+
ctrl.$setValidity('max', valid);
785+
return valid ? value : undefined;
786+
};
787+
788+
ctrl.$parsers.push(maxValidator);
789+
ctrl.$formatters.push(maxValidator);
790+
}
791+
792+
function getFirstThursday(year) {
793+
var d = 1, date;
794+
while(true) {
795+
date = new Date(year, 0, d++);
796+
if(date.getDay() === 4) {
797+
return date;
798+
}
799+
}
800+
}
801+
802+
function getThisThursday(date) {
803+
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + (4 - date.getDay()));
804+
}
805+
806+
var MILLISECONDS_PER_WEEK = 6.048e8;
807+
808+
function getWeek(date) {
809+
var firstThurs = getFirstThursday(date.getFullYear()),
810+
thisThurs = getThisThursday(date),
811+
diff = +thisThurs - +firstThurs;
812+
813+
return 1 + Math.round(diff / MILLISECONDS_PER_WEEK);
814+
}
815+
816+
function getTime(isoWeek) {
817+
if(isDate(isoWeek)) {
818+
return {
819+
year: isoWeek.getFullYear(),
820+
week: getWeek(isoWeek),
821+
time: +isoWeek
822+
};
823+
}
824+
825+
if(isString(isoWeek)) {
826+
WEEK_REGEXP.lastIndex = 0;
827+
var parts = WEEK_REGEXP.exec(isoWeek);
828+
if(parts) {
829+
var year = +parts[1],
830+
week = +parts[2],
831+
firstThurs = getFirstThursday(year),
832+
addDays = (week - 1) * 7;
833+
834+
return {
835+
time: +new Date(year, 0, firstThurs.getDate() + addDays),
836+
week: week,
837+
year: year
838+
};
839+
}
840+
}
841+
842+
return NaN;
843+
}
844+
}
845+
665846
function dateTimeLocalInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
666847
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
667848

src/ng/filter/filters.js

+35-2
Original file line numberDiff line numberDiff line change
@@ -228,6 +228,35 @@ function timeZoneGetter(date) {
228228
return paddedZone;
229229
}
230230

231+
function getFirstThursday(year) {
232+
var d = 1,
233+
date = new Date(year, 0, d);
234+
while(date.getDay() !== 4) {
235+
d++;
236+
date = new Date(year, 0, d);
237+
}
238+
return date;
239+
}
240+
241+
function getThursdayThisWeek(date) {
242+
var day = date.getDay(),
243+
d = date.getDate();
244+
245+
return new Date(date.getFullYear(), date.getMonth(), d + (4 - day));
246+
}
247+
248+
function weekGetter(size) {
249+
return function(date) {
250+
var firstThurs = getFirstThursday(date.getFullYear()),
251+
thisThurs = getThursdayThisWeek(date);
252+
253+
var diff = +thisThurs - +firstThurs,
254+
result = 1 + Math.round(diff / 6.048e8);
255+
256+
return padNumber(result, size);
257+
}
258+
}
259+
231260
function ampmGetter(date, formats) {
232261
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
233262
}
@@ -256,10 +285,12 @@ var DATE_FORMATS = {
256285
EEEE: dateStrGetter('Day'),
257286
EEE: dateStrGetter('Day', true),
258287
a: ampmGetter,
259-
Z: timeZoneGetter
288+
Z: timeZoneGetter,
289+
ww: weekGetter(2),
290+
w: weekGetter(1)
260291
};
261292

262-
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
293+
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,
263294
NUMBER_STRING = /^\-?\d+$/;
264295

265296
/**
@@ -294,6 +325,8 @@ var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+
294325
* * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
295326
* * `'a'`: am/pm marker
296327
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
328+
* * `'ww'`: ISO-8601 week of year (00-53)
329+
* * `'w'`: ISO-8601 week of year (0-53)
297330
*
298331
* `format` string can also be one of the following predefined
299332
* {@link guide/i18n localizable formats}:

test/ng/directive/inputSpec.js

+88
Original file line numberDiff line numberDiff line change
@@ -752,6 +752,94 @@ describe('input', function() {
752752

753753
// INPUT TYPES
754754

755+
describe('week', function (){
756+
it('should set the view if the model is valid ISO8601 week', function() {
757+
compileInput('<input type="week" ng-model="secondWeek"/>');
758+
759+
scope.$apply(function(){
760+
scope.secondWeek = '2013-W02';
761+
});
762+
763+
expect(inputElm.val()).toBe('2013-W02');
764+
});
765+
766+
it('should set the view if the model is a valid Date object', function (){
767+
compileInput('<input type="week" ng-model="secondWeek"/>');
768+
769+
scope.$apply(function(){
770+
scope.secondWeek = new Date(2013, 0, 11);
771+
});
772+
773+
expect(inputElm.val()).toBe('2013-W02');
774+
});
775+
776+
it('should set the model undefined if the input is an invalid week string', function () {
777+
compileInput('<input type="week" ng-model="value"/>');
778+
779+
scope.$apply(function(){
780+
scope.value = new Date(2013, 0, 11);
781+
});
782+
783+
784+
expect(inputElm.val()).toBe('2013-W02');
785+
786+
try {
787+
//set to text for browsers with datetime-local validation.
788+
inputElm[0].setAttribute('type', 'text');
789+
} catch(e) {
790+
//for IE8
791+
}
792+
793+
changeInputValueTo('stuff');
794+
expect(inputElm.val()).toBe('stuff');
795+
expect(scope.value).toBeUndefined();
796+
expect(inputElm).toBeInvalid();
797+
});
798+
799+
800+
801+
describe('min', function (){
802+
beforeEach(function (){
803+
compileInput('<input type="week" ng-model="value" name="alias" min="2013-W01" />');
804+
scope.$digest();
805+
});
806+
807+
it('should invalidate', function (){
808+
changeInputValueTo('2012-W12');
809+
expect(inputElm).toBeInvalid();
810+
expect(scope.value).toBeFalsy();
811+
expect(scope.form.alias.$error.min).toBeTruthy();
812+
});
813+
814+
it('should validate', function (){
815+
changeInputValueTo('2013-W03');
816+
expect(inputElm).toBeValid();
817+
expect(+scope.value).toBe(+new Date(2013, 0, 17));
818+
expect(scope.form.alias.$error.min).toBeFalsy();
819+
});
820+
});
821+
822+
describe('max', function(){
823+
beforeEach(function (){
824+
compileInput('<input type="week" ng-model="value" name="alias" max="2013-W01" />');
825+
scope.$digest();
826+
});
827+
828+
it('should validate', function (){
829+
changeInputValueTo('2012-W01');
830+
expect(inputElm).toBeValid();
831+
expect(+scope.value).toBe(+new Date(2012, 0, 5));
832+
expect(scope.form.alias.$error.max).toBeFalsy();
833+
});
834+
835+
it('should invalidate', function (){
836+
changeInputValueTo('2013-W03');
837+
expect(inputElm).toBeInvalid();
838+
expect(scope.value).toBeUndefined();
839+
expect(scope.form.alias.$error.max).toBeTruthy();
840+
});
841+
});
842+
});
755843

756844
describe('datetime-local', function () {
757845
it('should set the view if the model is valid ISO8601 local datetime', function() {

test/ng/filter/filtersSpec.js

+7-1
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ describe('filters', function() {
192192
var noon = new angular.mock.TzDate(+5, '2010-09-03T17:05:08.012Z'); //12pm
193193
var midnight = new angular.mock.TzDate(+5, '2010-09-03T05:05:08.123Z'); //12am
194194
var earlyDate = new angular.mock.TzDate(+5, '0001-09-03T05:05:08.000Z');
195-
195+
var secondWeek = new angular.mock.TzDate(+5, '2013-01-11T12:00:00.000Z'); //Friday Jan 11, 2012
196196
var date;
197197

198198
beforeEach(inject(function($filter) {
@@ -215,6 +215,12 @@ describe('filters', function() {
215215
});
216216

217217
it('should accept various format strings', function() {
218+
expect(date(secondWeek, 'yyyy-Ww')).
219+
toEqual('2013-W2');
220+
221+
expect(date(secondWeek, 'yyyy-Www')).
222+
toEqual('2013-W02');
223+
218224
expect(date(morning, "yy-MM-dd HH:mm:ss")).
219225
toEqual('10-09-03 07:05:08');
220226

0 commit comments

Comments
 (0)