Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ENG-688] Validated Form-Controls #721

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [Unreleased]
### Added
- Components
- `form-controls` - a form-input wrapper that takes a changeset

### Changed
- Components
- `project-contributors/list`
Expand Down
32 changes: 5 additions & 27 deletions app/utils/build-changeset.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,9 @@

import { assert } from '@ember/debug';
import { typeOf } from '@ember/utils';
import Changeset from 'ember-changeset';
import { ChangesetDef, ValidatorFunc } from 'ember-changeset/types';
import ModelRegistry from 'ember-data/types/registries/model';

import { ValidatedModelName } from 'ember-osf-web/models/osf-model';

// Lifted wholesale from https://github.com/offirgolan/ember-changeset-cp-validations/blob/master/addon/index.js
export default function buildChangeset<M extends ValidatedModelName>(model: ModelRegistry[M], options?: {}) {
assert('Object does not contain any validations', typeOf(model.validations) === 'instance');
let useOptions = {};
if (options !== undefined) {
useOptions = options;
}
const validationMap = model.validations.validatableAttributes.reduce(
(o: any, attr: string) => {
o[attr] = true; // eslint-disable-line no-param-reassign
return o;
},
{},
);
import lookupValidator from 'ember-changeset-validations';
import { ChangesetDef, Config, ValidatorFunc } from 'ember-changeset/types';

const validateFn: ValidatorFunc = async params => {
const { validations } = await model.validateAttribute(params.key, params.newValue);
return validations.isValid ? true : validations.message;
};
interface ValidationMap { [s: string]: ValidatorFunc | ValidatorFunc[]; }

return new Changeset(model, validateFn, validationMap, useOptions) as ChangesetDef;
export default function buildChangeset(target: object, validationMap: ValidationMap, options?: Config) {
return new Changeset(target, lookupValidator(validationMap), validationMap, options) as ChangesetDef;
}
26 changes: 26 additions & 0 deletions lib/handbook/addon/docs/components/form-controls/controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { service } from '@ember-decorators/service';
import Controller from '@ember/controller';
import { action } from '@ember/object';
import { ChangesetDef } from 'ember-changeset/types';
import Toast from 'ember-toastr/services/toast';

import Node from 'ember-osf-web/models/node';

import { nodeValidation } from './validation';

export default class FormController extends Controller {
@service toast!: Toast;

validation = nodeValidation;
node = Node;
changeset!: ChangesetDef;

@action
submit() {
this.changeset.validate();
if (this.changeset.isValid) {
this.changeset.save({});
this.toast.success('Saved!');
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<DocsDemo as |demo|>
jamescdavis marked this conversation as resolved.
Show resolved Hide resolved
<demo.example @name='form-controls.demo-default.hbs'>
<form {{on 'submit' (prevent-default this.submit)}}>
<FormControls
@changeset={{this.changeset}}
as |form|
>
<form.text
@label='Title'
@valuePath='title'
/>
<form.text
@label='Description'
@valuePath='description'
/>
</FormControls>
<OsfButton
@type='primary'
@buttonType='submit'
>
Submit
</OsfButton>
</form>
</demo.example>

<demo.snippet @name='form-controls.demo-default.hbs' />
</DocsDemo>
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<DocsDemo as |demo|>
<demo.example @name='form-controls.demo-disabled.hbs'>
<form {{on 'submit' (prevent-default this.submit)}}>
<FormControls
@changeset={{this.changeset}}
@disabled={{this.disabled}}
as |form|
>
<form.text
@label='Title'
@valuePath='title'
/>
<form.text
@label='Description'
@valuePath='description'
/>
</FormControls>
<OsfButton
@type='primary'
@buttonType='submit'
@disabled={{this.disabled}}
>
Submit
</OsfButton>
</form>
</demo.example>

<OsfButton
@class='center-block m-b-lg'
@onClick={{action (mut this.disabled) (not this.disabled)}}
>
set: disabled = {{not this.disabled}}
</OsfButton>

<demo.snippet @name='form-controls.demo-disabled.hbs' />
</DocsDemo>
16 changes: 16 additions & 0 deletions lib/handbook/addon/docs/components/form-controls/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Route from '@ember/routing/route';

import buildChangeset from 'ember-osf-web/utils/build-changeset';

import FormController from './controller';

export default class FormControls extends Route {
setupController(controller: FormController) {
const model = {
title: '',
description: '',
};
const changeset = buildChangeset(model, controller.validation);
controller.set('changeset', changeset);
}
}
28 changes: 28 additions & 0 deletions lib/handbook/addon/docs/components/form-controls/template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# form-controls
Takes a changeset and yields validated form components

### Params
The only param that `<FormControls />` takes is a changeset for the current form being created

### Yielded hash
When invoked in a form, `<FormControls />` yields a hash with the following keys:

* Several `validated-model-form/*` components with common arguments (`model`, `changeset`, `shouldShowMessages`, `disabled`) already bound:
* `checkbox`
* `checkboxes`
* `date`
* `recaptcha`
* `text`
* `textarea`

## Demo: Default
{{docs/components/form-controls/demo-default
submit=(action this.submit)
changeset=this.changeset
}}

## Demo: Disabled
{{docs/components/form-controls/demo-disabled
submit=(action this.submit)
changeset=this.changeset
}}
12 changes: 12 additions & 0 deletions lib/handbook/addon/docs/components/form-controls/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { ValidationObject } from 'ember-changeset-validations';
import { validatePresence } from 'ember-changeset-validations/validators';
import NodeModel from 'ember-osf-web/models/node';

export const nodeValidation: ValidationObject<NodeModel> = {
title: [
validatePresence(true),
],
description: [
validatePresence(true),
],
};
1 change: 1 addition & 0 deletions lib/handbook/addon/docs/template.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
<nav.item @label='contributor-list' @route='docs.components.contributor-list' />
<nav.item @label='copyable-text' @route='docs.components.copyable-text' />
<nav.item @label='delete-button' @route='docs.components.delete-button' />
<nav.item @label='form-controls' @route='docs.components.form-controls' />
<nav.item @label='institutions-widget' @route='docs.components.institutions-widget' />
<nav.item @label='loading-indicator' @route='docs.components.loading-indicator' />
<nav.item @label='new-project-modal' @route='docs.components.new-project-modal' />
Expand Down
1 change: 1 addition & 0 deletions lib/handbook/addon/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ export default buildRoutes(function() {
this.route('contributor-list');
this.route('copyable-text');
this.route('delete-button');
this.route('form-controls');
this.route('institutions-widget');
this.route('loading-indicator');
this.route('new-project-modal');
Expand Down
5 changes: 4 additions & 1 deletion lib/handbook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"@ember/render-modifiers": "*",
"ember-angle-bracket-invocation-polyfill": "*",
"ember-bootstrap": "*",
"ember-changeset": "*",
"ember-changeset-validations": "*",
"ember-cli-addon-docs": "*",
"ember-cli-addon-docs-typedoc": "*",
"ember-cli-babel": "*",
Expand All @@ -16,10 +18,11 @@
"ember-cli-typescript": "*",
"ember-code-snippet": "*",
"ember-component-attributes": "*",
"ember-content-placeholders": "https://github.com/cos-forks/ember-content-placeholders#master#2018-07-19",
"ember-content-placeholders": "*",
"ember-cp-validations": "*",
"ember-css-modules": "*",
"ember-css-modules-sass": "*",
"ember-event-helpers": "*",
"ember-font-awesome": "*",
"ember-on-modifier": "*",
"ember-onbeforeunload": "*",
Expand Down
18 changes: 18 additions & 0 deletions lib/osf-components/addon/components/form-controls/component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { layout, tagName } from '@ember-decorators/component';
import Component from '@ember/component';
import Changeset from 'ember-changeset';

import defaultTo from 'ember-osf-web/utils/default-to';

import template from './template';

@layout(template)
jamescdavis marked this conversation as resolved.
Show resolved Hide resolved
@tagName('')
export default class FormControls extends Component {
// Required parameters
changeset!: Changeset;

// Optional parameters
disabled: boolean = defaultTo(this.disabled, false);
jamescdavis marked this conversation as resolved.
Show resolved Hide resolved
shouldShowMessages: boolean = defaultTo(this.shouldShowMessages, true);
}
51 changes: 51 additions & 0 deletions lib/osf-components/addon/components/form-controls/template.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{{yield (hash
checkbox=(
component
'validated-input/checkbox'
changeset=@changeset
shouldShowMessages=this.shouldShowMessages
disabled=this.disabled
)
date=(
component
'validated-input/date'
changeset=@changeset
shouldShowMessages=this.shouldShowMessages
disabled=this.disabled
)
recaptcha=(
component
'validated-input/recaptcha'
changeset=@changeset
shouldShowMessages=this.shouldShowMessages
disabled=this.inputsDisabled
)
text=(
component
'validated-input/text'
changeset=@changeset
shouldShowMessages=this.shouldShowMessages
disabled=this.disabled
)
textarea=(
component
'validated-input/textarea'
changeset=@changeset
jamescdavis marked this conversation as resolved.
Show resolved Hide resolved
shouldShowMessages=this.shouldShowMessages
disabled=this.disabled
)
select=(
component
'validated-input/power-select'
changeset=@changeset
shouldShowMessages=this.shouldShowMessages
disabled=this.disabled
)
custom=(
component
'validated-input/custom'
changeset=@changeset
shouldShowMessages=this.shouldShowMessages
disabled=this.disabled
)
)}}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export default class ValidatedXInputWrapper extends Component {
// Optional arguments
errors?: string;
label?: string;
id?: string;

@className
@equal('validationStatus', ValidationStatus.HasError)
Expand All @@ -34,6 +35,6 @@ export default class ValidatedXInputWrapper extends Component {

@computed('elementId', 'valuePath')
get inputElementId() {
return `${this.elementId}__${this.valuePath}`;
return this.id ? this.id : `${this.elementId}__${this.valuePath}`;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ import { action } from '@ember-decorators/object';
import { alias, or } from '@ember-decorators/object/computed';
import { service } from '@ember-decorators/service';
import Component from '@ember/component';
import { assert } from '@ember/debug';
import { set } from '@ember/object';
import { ChangesetDef } from 'ember-changeset/types';
import { typeOf } from '@ember/utils';
import Changeset from 'ember-changeset';
import { ChangesetDef, ValidatorFunc } from 'ember-changeset/types';

import { task } from 'ember-concurrency';
import DS from 'ember-data';
import ModelRegistry from 'ember-data/types/registries/model';
Expand All @@ -13,7 +17,6 @@ import Toast from 'ember-toastr/services/toast';
import { requiredAction } from 'ember-osf-web/decorators/component';
import { ValidatedModelName } from 'ember-osf-web/models/osf-model';
import Analytics from 'ember-osf-web/services/analytics';
import buildChangeset from 'ember-osf-web/utils/build-changeset';
import defaultTo from 'ember-osf-web/utils/default-to';

import template from './template';
Expand Down Expand Up @@ -57,7 +60,7 @@ export default class ValidatedModelForm<M extends ValidatedModelName> extends Co
if (this.modelName && this.recreateModel) {
set(this, 'model', this.store.createRecord(this.modelName, this.modelProperties));
if (this.model !== undefined) {
set(this, 'changeset', buildChangeset(this.model));
set(this, 'changeset', this.buildChangeset(this.model));
this._onDirtChange();
}
}
Expand All @@ -82,7 +85,7 @@ export default class ValidatedModelForm<M extends ValidatedModelName> extends Co
this.model = this.store.createRecord(this.modelName, this.modelProperties);
}
if (!this.changeset && this.model) {
const changeset = buildChangeset(this.model);
const changeset = this.buildChangeset(this.model);
set(this, 'changeset', changeset);
this._onDirtChange();
changeset.on('afterValidation', () => {
Expand All @@ -105,6 +108,30 @@ export default class ValidatedModelForm<M extends ValidatedModelName> extends Co
}
}

// Lifted wholesale from https://github.com/offirgolan/ember-changeset-cp-validations/blob/master/addon/index.js
// tslint:disable-next-line: no-shadowed-variable
buildChangeset<M extends ValidatedModelName>(model: ModelRegistry[M], options?: {}) {
assert('Object does not contain any validations', typeOf(model.validations) === 'instance');
let useOptions = {};
if (options !== undefined) {
useOptions = options;
}
const validationMap = model.validations.validatableAttributes.reduce(
(o: any, attr: string) => {
o[attr] = true; // eslint-disable-line no-param-reassign
return o;
},
{},
);

const validateFn: ValidatorFunc = async params => {
const { validations } = await model.validateAttribute(params.key, params.newValue);
return validations.isValid ? true : validations.message;
};

return new Changeset(model, validateFn, validationMap, useOptions) as ChangesetDef;
}

@action
rollback() {
this.changeset.rollback();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from 'osf-components/components/form-controls/component';
Loading