Skip to content

[EMB-598] Validated-changeset-form #609

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

Closed
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { action, computed } from '@ember-decorators/object';
import { reads } from '@ember-decorators/object/computed';
import { service } from '@ember-decorators/service';
import Controller from '@ember/controller';
import { ChangesetDef } from 'ember-changeset/types';
import DS from 'ember-data';
import Toast from 'ember-toastr/services/toast';

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

import { nodeValidation } from './validation';

export default class ValidatedChangesetFormController extends Controller {
@service store!: DS.Store;
@service toast!: Toast;

@reads('model.taskInstance.value')
existingNode?: Node;
emptyNode = new Node();
createDirt = false;
editDirt = false;
validation = nodeValidation;

// BEGIN-SNIPPET validated-changeset-form.controller.ts
@action
async saveExisting(changeset: ChangesetDef) {
changeset.save({});
this.toast.success('Saved!');
}

@action
async saveNew(changeset: ChangesetDef) {
changeset.save({});
this.toast.success('Saved!');
this.emptyNode = new Node();
}

@action
onWillDestroy() {
if (this.get('isDirty')) {
// Do something cool here
}
}

// Since there are two forms on the page, we need to report on both
@action
changeDirtEditForm(dirt: boolean) {
this.set('editDirt', dirt);
}

@action
changeDirtCreateForm(dirt: boolean) {
this.set('createDirt', dirt);
}

@computed('createDirt', 'editDirt')
get isDirty() {
return this.createDirt || this.editDirt;
}
// END-SNIPPET
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<DocsDemo as |demo|>
<demo.example @name='validated-changeset-form.demo-create.hbs'>
<ValidatedChangesetForm
@onSave={{action @onSave this.changeset}}
@changeset={{changeset this.node this.validation}}
@onDirtChange={{@changeDirtCreateForm}}
as |form|
>
<form.text
@valuePath='title'
@label='Title'
/>
<form.textarea
@valuePath='description'
@label='Description'
/>
<BsButton
@buttonType='submit'
@disabled={{form.disabled}}
>
Save
</BsButton>
</ValidatedChangesetForm>
</demo.example>

<demo.snippet @name='validated-model-form.demo-create.hbs' />
</DocsDemo>
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<DocsDemo as |demo|>
{{#if this.node}}
<demo.example @name='validated-changeset-form.demo-edit.hbs'>
<ValidatedChangesetForm
@onSave={{action this.onSave changeset}}
@onWillDestroy={{action this.onWillDestroy}}
@changeset={{changeset this.existingNode this.validation}}
@disabled={{this.model.taskInstance.isRunning}}
@onDirtChange={{this.changeDirtEditForm}}
as |form|
>
<form.text
@valuePath='title'
@label='Title'
/>
<form.textarea
@valuePath='description'
@label='Description'
/>
<BsButton
@onClick={{action form.rollback}}
@disabled={{not form.isDirty}}
>
Cancel
</BsButton>
<BsButton
@buttonType='submit'
@disabled={{form.disabled}}
>
Save
</BsButton>
</ValidatedChangesetForm>
</demo.example>

<demo.snippet @name='validated-changeset-form.demo-edit.hbs' />
<demo.snippet
@name='validated-changeset-form.on-will-destroy.ts'
@label='controller.ts'
/>
<demo.snippet
@name='validated-changeset-form.is-page-dirty.ts'
@label='route.ts'
/>
{{/if}}
</DocsDemo>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { computed } from '@ember-decorators/object';
import Route from '@ember/routing/route';
import { task } from 'ember-concurrency';
import ConfirmationMixin from 'ember-onbeforeunload/mixins/confirmation';

import ValidatedModelFormController from './controller';

export default class ValidatedModelFormRoute extends Route.extend(ConfirmationMixin, {
modelTask: task(function *(this: ValidatedModelFormRoute) {
return yield this.store.findRecord('node', 'extng');
}),
}) {
model() {
return {
taskInstance: this.modelTask.perform(),
};
}

// BEGIN-SNIPPET validated-model-form.route.ts
// This tells ember-onbeforeupload's ConfirmationMixin whether or not to stop transitions
@computed('controller.isDirty')
get isPageDirty() {
const controller = this.controller as ValidatedModelFormController;
return () => controller.get('isDirty');
}
// END-SNIPPET
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# validated-changeset-form
Helps build validated forms without necessarily needing a model.

This component is appropriate if:
- You want a form
- You have defined validations specific for that form

Renders a `<form>` element, provides tools to easily build that form, and handles
creating (if necessary), validating, and saving the model.

### Params
* `changeset` (required): Changeset to use for this form.
* `onSave(changeset)` (required): Action called after the model is successfully validated and saved.
* `onError(error, changeset)` (optional): Action called if saving the model fails.
* `onWillDestroy()` (optional): Action called if you transition.
* `onDirtChange(dirt: Boolean)` (optional): Action called When validation is run to pass along `changeset.isDirty`.
* `disabled` (default `false`)

### Yielded hash
When invoked in block form, `validated-model-form` yields a hash with the following keys:

* `changeset`: The changeset for this particular form.
* `disabled`: `true` when the model is being saved or the passed-in `disabled` param is `true`.
* `rollback`: Action to allow the form components to rollback the changes
* `submit`: Action to submit the form. Alternately, you can put a `<button type="submit">` in the form.
* Several `validated-input/*` components with common arguments (`model`, `changeset`, `shouldShowMessages`, `disabled`) already bound:
* `checkbox`
* `checkboxes`
* `date`
* `recaptcha`
* `text`
* `textarea`

## Demo: Create
{{docs/components/validated-changeset-form/demo-create
onSave=(action this.saveNew)
node=this.emptyNode
changeDirtCreateForm=(action this.changeDirtCreateForm)
}}

## Demo: Edit
This also shows how to use the `rollback`, `onDirtChange()`, `onWillDestroy()`, and `onSave()` actions.

{{docs/components/validated-changeset-form/demo-edit
onSave=(action this.saveExisting)
onWillDestroy=(action this.onWillDestroy)
node=this.existingNode
changeDirtEditForm=(action this.changeDirtEditForm)
}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
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),
],
};
3 changes: 2 additions & 1 deletion lib/handbook/addon/docs/template.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,17 @@
<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='osf-link' @route='docs.components.osf-link' />
<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' />
<nav.item @label='new-project-navigation-modal' @route='docs.components.new-project-navigation-modal' />
<nav.item @label='osf-button' @route='docs.components.osf-button' />
<nav.item @label='osf-link' @route='docs.components.osf-link' />
<nav.item @label='osf-link' @route='docs.components.osf-link' />
<nav.item @label='panel' @route='docs.components.panel' />
<nav.item @label='placeholder' @route='docs.components.placeholder' />
<nav.item @label='tags-widget' @route='docs.components.tags-widget' />
<nav.item @label='validated-changeset-form' @route='docs.components.validated-changeset-form' />
<nav.item @label='validated-model-form' @route='docs.components.validated-model-form' />
</viewer.nav>

Expand Down
3 changes: 2 additions & 1 deletion lib/handbook/addon/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,17 @@ export default buildRoutes(function() {
this.route('contributor-list');
this.route('copyable-text');
this.route('delete-button');
this.route('osf-link');
this.route('institutions-widget');
this.route('loading-indicator');
this.route('new-project-modal');
this.route('new-project-navigation-modal');
this.route('osf-button');
this.route('osf-link');
this.route('osf-link');
this.route('panel');
this.route('placeholder');
this.route('tags-widget');
this.route('validated-changeset-form');
this.route('validated-model-form');
});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { layout } from '@ember-decorators/component';
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 { ChangesetDef } from 'ember-changeset/types';
import { task } from 'ember-concurrency';
import DS from 'ember-data';
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 defaultTo from 'ember-osf-web/utils/default-to';

import template from './template';

@layout(template)
export default class ValidatedChangesetForm<M extends ValidatedModelName> extends Component {
// Required arguments
@requiredAction onSave!: (changeset: ChangesetDef) => void;

// Optional arguments
onError?: (e: object, changeset: ChangesetDef) => void;
onWillDestroy?: (changeset?: ChangesetDef) => void;
disabled: boolean = defaultTo(this.disabled, false);
changeset!: ChangesetDef;
recreateModel: boolean = defaultTo(this.recreateModel, false);

// Private properties
@service store!: DS.Store;
@service analytics!: Analytics;
@service toast!: Toast;

shouldShowMessages: boolean = false;
onDirtChange?: (dirt: boolean) => boolean;

@or('disabled', 'saveTask.isRunning')
inputsDisabled!: boolean;

@alias('changeset.isDirty')
isDirty!: boolean;

saveTask = task(function *(this: ValidatedChangesetForm<M>) {
yield this.changeset.validate();

if (this.changeset.get('isValid')) {
try {
this.onSave(this.changeset);
this.set('shouldShowMessages', false);
} catch (e) {
if (this.onError) {
this.onError(e, this.changeset);
} else {
this.toast.error(e);
}
throw e;
}
} else {
this.set('shouldShowMessages', true);
}
});

constructor(...args: any[]) {
super(...args);
const { changeset } = this;
this._onDirtChange();
changeset.on('afterValidation', () => {
this._onDirtChange();
});
}

_onDirtChange() {
if (typeof (this.onDirtChange) !== 'undefined') {
this.onDirtChange(this.isDirty);
}
}

willDestroy() {
if (this.onWillDestroy !== undefined) {
this.onWillDestroy(this.changeset);
}
}

@action
rollback() {
this.changeset.rollback();
}
}
Loading