Skip to content

Commit

Permalink
feat: scroll first invalid element into view (#733)
Browse files Browse the repository at this point in the history
* feat: scroll first invalid element into view

* fix: hide this feature behind a config flag

* docs: enable and document feature flag
  • Loading branch information
derrabauke authored Feb 3, 2022
1 parent 95f4099 commit ae7c8b2
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
10 changes: 10 additions & 0 deletions addon/components/validated-form.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getOwner } from "@ember/application";
import { action } from "@ember/object";
import { scheduleOnce } from "@ember/runloop";
import Component from "@glimmer/component";
Expand All @@ -14,6 +15,10 @@ export default class ValidatedFormComponent extends Component {

constructor(...args) {
super(...args);
this.config =
getOwner(this).resolveRegistration("config:environment")[
"ember-validated-form"
];

if (this.args.model && this.args.model.validate) {
scheduleOnce("actions", this, "validateModel", this.args.model);
Expand Down Expand Up @@ -44,6 +49,11 @@ export default class ValidatedFormComponent extends Component {
await model.validate();

if (model.get("isInvalid")) {
if (this.config?.features?.scrollErrorIntoView && model.errors[0]?.key) {
document
.querySelector(`[name=${model.errors[0].key}]`)
?.scrollIntoView();
}
this.runCallback(PROP_ON_INVALID_SUBMIT);
} else {
this.runCallback(PROP_ON_SUBMIT);
Expand Down
10 changes: 10 additions & 0 deletions tests/dummy/app/snippets/config-features.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
var ENV = {
// ...
"ember-validated-form": {
theme: "bootstrap",
features: {
scrollErrorIntoView: true,
}
},
// ...
};
7 changes: 7 additions & 0 deletions tests/dummy/app/templates/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,10 @@ For instance:
{{demo.snippet 'permanent-custom-hint-component-template.hbs' label='permanent-custom-hint.hbs'}}
{{/docs-demo}}
<!-- prettier-ignore-end -->

## Other features

If you want to scroll the first invalid field into view, you can set the
`scrollErrorIntoView` property to `true` (default: false).

{{docs-snippet name='config-features.js' title='config/environment.js'}}
3 changes: 3 additions & 0 deletions tests/dummy/config/environment.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ module.exports = function (environment) {
defaults: {
hint: "permanent-custom-hint",
},
features: {
scrollErrorIntoView: false,
},
},
EmberENV: {
FEATURES: {
Expand Down

0 comments on commit ae7c8b2

Please sign in to comment.