feat(forms): add support for checkbox

This commit is contained in:
vsavkin 2015-02-07 14:14:07 -08:00
parent 74f92c6a79
commit 4b24734855
2 changed files with 169 additions and 57 deletions

View File

@ -1,7 +1,7 @@
import {TemplateConfig, Component, Decorator, NgElement, Ancestor} from 'angular2/core'; import {TemplateConfig, Component, Decorator, NgElement, Ancestor, onChange} from 'angular2/core';
import {DOM} from 'angular2/src/facade/dom'; import {DOM} from 'angular2/src/facade/dom';
import {isBlank, isPresent} from 'angular2/src/facade/lang'; import {isBlank, isPresent, CONST} from 'angular2/src/facade/lang';
import {ListWrapper} from 'angular2/src/facade/collection'; import {StringMapWrapper, ListWrapper} from 'angular2/src/facade/collection';
import {ControlGroup, Control} from './model'; import {ControlGroup, Control} from './model';
class ControlGroupDirectiveBase { class ControlGroupDirectiveBase {
@ -9,73 +9,126 @@ class ControlGroupDirectiveBase {
findControl(name:string):Control { return null; } findControl(name:string):Control { return null; }
} }
export class ControlDirectiveBase { @CONST()
_groupDecorator:ControlGroupDirectiveBase; export class ControlValueAccessor {
_el:NgElement; readValue(el){}
_controlName:string; writeValue(el, value):void {}
}
constructor(groupDecorator, el:NgElement) { @CONST()
this._groupDecorator = groupDecorator; class DefaultControlValueAccessor extends ControlValueAccessor {
this._el = el; constructor() {
DOM.on(el.domElement, "change", (_) => this._updateControl()); super();
} }
set controlName(name:string) { readValue(el) {
this._controlName = name; return el.value;
this._groupDecorator.addDirective(this);
this._updateDOM();
} }
get controlName() { writeValue(el, value):void {
return this._controlName; el.value = value;
}
}
@CONST()
class CheckboxControlValueAccessor extends ControlValueAccessor {
constructor() {
super();
} }
//TODO:vsavkin: Remove it once change detection lifecycle callbacks are available readValue(el):boolean {
isInitialized():boolean { return el.checked;
return isPresent(this._controlName);
} }
_updateDOM() { writeValue(el, value:boolean):void {
// remove it once all DOM write go through a queue el.checked = value;
if (this.isInitialized()) {
var inputElement:any = this._el.domElement;
inputElement.value = this._control().value;
}
} }
}
_updateControl() { var controlValueAccessors = {
var inputElement:any = this._el.domElement; "checkbox" : new CheckboxControlValueAccessor(),
this._control().value = inputElement.value; "text" : new DefaultControlValueAccessor()
} };
_control() { function controlValueAccessorFor(controlType:string):ControlValueAccessor {
return this._groupDecorator.findControl(this._controlName); var accessor = StringMapWrapper.get(controlValueAccessors, controlType);
if (isPresent(accessor)) {
return accessor;
} else {
return StringMapWrapper.get(controlValueAccessors, "text");
} }
} }
export class ControlDirectiveBase {
_groupDecorator:ControlGroupDirectiveBase;
_el:NgElement;
controlName:string;
type:string;
valueAccessor:ControlValueAccessor;
constructor(groupDecorator, el:NgElement) {
this._groupDecorator = groupDecorator;
this._el = el;
}
_initialize() {
if (isBlank(this.valueAccessor)) {
this.valueAccessor = controlValueAccessorFor(this.type);
}
this._groupDecorator.addDirective(this);
this._updateDomValue();
DOM.on(this._el.domElement, "change", (_) => this._updateControlValue());
}
_updateDomValue() {
this.valueAccessor.writeValue(this._el.domElement, this._control().value);
}
_updateControlValue() {
this._control().value = this.valueAccessor.readValue(this._el.domElement);
}
_control() {
return this._groupDecorator.findControl(this.controlName);
}
}
@Decorator({ @Decorator({
lifecycle: [onChange],
selector: '[control-name]', selector: '[control-name]',
bind: { bind: {
'control-name' : 'controlName' 'control-name' : 'controlName',
'type' : 'type'
} }
}) })
export class ControlNameDirective extends ControlDirectiveBase { export class ControlNameDirective extends ControlDirectiveBase {
constructor(@Ancestor() groupDecorator:ControlGroupDirective, el:NgElement) { constructor(@Ancestor() groupDecorator:ControlGroupDirective, el:NgElement) {
super(groupDecorator, el); super(groupDecorator, el);
} }
onChange(_) {
this._initialize();
}
} }
@Decorator({ @Decorator({
lifecycle: [onChange],
selector: '[control]', selector: '[control]',
bind: { bind: {
'control' : 'controlName' 'control' : 'controlName',
'type' : 'type'
} }
}) })
export class ControlDirective extends ControlDirectiveBase { export class ControlDirective extends ControlDirectiveBase {
constructor(@Ancestor() groupDecorator:NewControlGroupDirective, el:NgElement) { constructor(@Ancestor() groupDecorator:NewControlGroupDirective, el:NgElement) {
super(groupDecorator, el); super(groupDecorator, el);
} }
onChange(_) {
this._initialize();
}
} }
@Decorator({ @Decorator({
@ -95,7 +148,7 @@ export class ControlGroupDirective extends ControlGroupDirectiveBase {
set controlGroup(controlGroup:ControlGroup) { set controlGroup(controlGroup:ControlGroup) {
this._controlGroup = controlGroup; this._controlGroup = controlGroup;
ListWrapper.forEach(this._directives, (cd) => cd._updateDOM()); ListWrapper.forEach(this._directives, (cd) => cd._updateDomValue());
} }
addDirective(c:ControlNameDirective) { addDirective(c:ControlNameDirective) {
@ -144,10 +197,8 @@ export class NewControlGroupDirective extends ControlGroupDirectiveBase {
_createControlGroup():ControlGroup { _createControlGroup():ControlGroup {
var controls = ListWrapper.reduce(this._directives, (memo, cd) => { var controls = ListWrapper.reduce(this._directives, (memo, cd) => {
if (cd.isInitialized()) { var initControlValue = this._initData[cd.controlName];
var initControlValue = this._initData[cd.controlName]; memo[cd.controlName] = new Control(initControlValue);
memo[cd.controlName] = new Control(initControlValue);
}
return memo; return memo;
}, {}); }, {});
return new ControlGroup(controls); return new ControlGroup(controls);
@ -157,3 +208,8 @@ export class NewControlGroupDirective extends ControlGroupDirectiveBase {
return this._controlGroup.value; return this._controlGroup.value;
} }
} }
export var FormDirectives = [
ControlGroupDirective, ControlNameDirective,
ControlDirective, NewControlGroupDirective
];

View File

@ -8,9 +8,10 @@ import {NativeShadowDomStrategy} from 'angular2/src/core/compiler/shadow_dom_str
import {Injector} from 'angular2/di'; import {Injector} from 'angular2/di';
import {DOM} from 'angular2/src/facade/dom'; import {DOM} from 'angular2/src/facade/dom';
import {Component, TemplateConfig} from 'angular2/core'; import {Component, Decorator, TemplateConfig} from 'angular2/core';
import {ControlDirective, ControlNameDirective, ControlGroupDirective, NewControlGroupDirective, import {ControlGroupDirective, ControlNameDirective,
Control, ControlGroup} from 'angular2/forms'; ControlDirective, NewControlGroupDirective,
Control, ControlGroup, ControlValueAccessor} from 'angular2/forms';
import {TemplateLoader} from 'angular2/src/core/compiler/template_loader'; import {TemplateLoader} from 'angular2/src/core/compiler/template_loader';
import {XHRMock} from 'angular2/src/mock/xhr_mock'; import {XHRMock} from 'angular2/src/mock/xhr_mock';
@ -36,11 +37,6 @@ export function main() {
}); });
} }
function formComponent(view) {
// TODO: vsavkin remove when view variables work
return view.elementInjectors[0].getComponent();
}
describe("integration tests", () => { describe("integration tests", () => {
it("should initialize DOM elements with the given form object", (done) => { it("should initialize DOM elements with the given form object", (done) => {
var ctx = new MyComp(new ControlGroup({ var ctx = new MyComp(new ControlGroup({
@ -48,7 +44,7 @@ export function main() {
})); }));
var t = `<div [control-group]="form"> var t = `<div [control-group]="form">
<input [control-name]="'login'"> <input type="text" control-name="login">
</div>`; </div>`;
compile(MyComp, t, ctx, (view) => { compile(MyComp, t, ctx, (view) => {
@ -65,7 +61,7 @@ export function main() {
var ctx = new MyComp(form); var ctx = new MyComp(form);
var t = `<div [control-group]="form"> var t = `<div [control-group]="form">
<input [control-name]="'login'"> <input type="text" control-name="login">
</div>`; </div>`;
compile(MyComp, t, ctx, (view) => { compile(MyComp, t, ctx, (view) => {
@ -86,7 +82,7 @@ export function main() {
var ctx = new MyComp(form); var ctx = new MyComp(form);
var t = `<div [control-group]="form"> var t = `<div [control-group]="form">
<input [control-name]="'login'"> <input type="text" control-name="login">
</div>`; </div>`;
compile(MyComp, t, ctx, (view) => { compile(MyComp, t, ctx, (view) => {
@ -108,7 +104,7 @@ export function main() {
}), "one"); }), "one");
var t = `<div [control-group]="form"> var t = `<div [control-group]="form">
<input [control-name]="name"> <input type="text" [control-name]="name">
</div>`; </div>`;
compile(MyComp, t, ctx, (view) => { compile(MyComp, t, ctx, (view) => {
@ -123,11 +119,51 @@ export function main() {
}); });
}); });
describe("different control types", () => {
it("should support type=checkbox", (done) => {
var ctx = new MyComp(new ControlGroup({"checkbox": new Control(true)}));
var t = `<div [control-group]="form">
<input type="checkbox" control-name="checkbox">
</div>`;
compile(MyComp, t, ctx, (view) => {
var input = queryView(view, "input")
expect(input.checked).toBe(true);
input.checked = false;
dispatchEvent(input, "change");
expect(ctx.form.value).toEqual({"checkbox" : false});
done();
});
});
it("should support custom value accessors", (done) => {
var ctx = new MyComp(new ControlGroup({"name": new Control("aa")}));
var t = `<div [control-group]="form">
<input type="text" control-name="name" wrapped-value>
</div>`;
compile(MyComp, t, ctx, (view) => {
var input = queryView(view, "input")
expect(input.value).toEqual("!aa!");
input.value = "!bb!";
dispatchEvent(input, "change");
expect(ctx.form.value).toEqual({"name" : "bb"});
done();
});
});
});
describe("declarative forms", () => { describe("declarative forms", () => {
it("should initialize dom elements", (done) => { it("should initialize dom elements", (done) => {
var t = `<div [new-control-group]="{'login': 'loginValue', 'password':'passValue'}"> var t = `<div [new-control-group]="{'login': 'loginValue', 'password':'passValue'}">
<input id="login" [control]="'login'"> <input type="text" id="login" control="login">
<input id="password" [control]="'password'"> <input type="password" id="password" control="password">
</div>`; </div>`;
compile(MyComp, t, new MyComp(), (view) => { compile(MyComp, t, new MyComp(), (view) => {
@ -142,8 +178,8 @@ export function main() {
}); });
it("should update the control group values on DOM change", (done) => { it("should update the control group values on DOM change", (done) => {
var t = `<div [new-control-group]="{'login': 'loginValue'}"> var t = `<div #form [new-control-group]="{'login': 'loginValue'}">
<input [control]="'login'"> <input type="text" control="login">
</div>`; </div>`;
compile(MyComp, t, new MyComp(), (view) => { compile(MyComp, t, new MyComp(), (view) => {
@ -152,7 +188,8 @@ export function main() {
input.value = "updatedValue"; input.value = "updatedValue";
dispatchEvent(input, "change"); dispatchEvent(input, "change");
expect(formComponent(view).value).toEqual({'login': 'updatedValue'}); var form = view.contextWithLocals.get("form");
expect(form.value).toEqual({'login': 'updatedValue'});
done(); done();
}); });
}); });
@ -166,7 +203,7 @@ export function main() {
template: new TemplateConfig({ template: new TemplateConfig({
inline: "", inline: "",
directives: [ControlGroupDirective, ControlNameDirective, directives: [ControlGroupDirective, ControlNameDirective,
ControlDirective, NewControlGroupDirective] ControlDirective, NewControlGroupDirective, WrappedValue]
}) })
}) })
class MyComp { class MyComp {
@ -178,3 +215,22 @@ class MyComp {
this.name = name; this.name = name;
} }
} }
class WrappedValueAccessor extends ControlValueAccessor {
readValue(el){
return el.value.substring(1, el.value.length - 1);
}
writeValue(el, value):void {
el.value = `!${value}!`;
}
}
@Decorator({
selector:'[wrapped-value]'
})
class WrappedValue {
constructor(cd:ControlNameDirective) {
cd.valueAccessor = new WrappedValueAccessor();
}
}