This repository has been archived by the owner on May 3, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
feat: rich error message POC #4
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
import { | ||
AfterViewInit, | ||
ChangeDetectorRef, | ||
HostBinding, | ||
Input, | ||
OnDestroy, | ||
} from '@angular/core'; | ||
import { AbstractControl } from '@angular/forms'; | ||
import { merge, NEVER, Subject } from 'rxjs'; | ||
import { filter, map, switchMap, takeUntil, tap } from 'rxjs/operators'; | ||
import { ErrorsConfiguration } from './errors-configuration'; | ||
import { ErrorsDirective } from './errors.directive'; | ||
import { NoParentNgxErrorsError, ValueMustBeStringError } from './ngx-errors'; | ||
|
||
export const defaultConfig = new ErrorsConfiguration(); | ||
|
||
export class ErrorBase implements AfterViewInit, OnDestroy { | ||
@HostBinding('hidden') | ||
hidden = true; | ||
|
||
@Input('ngxError') errorName: string; | ||
|
||
private destroy = new Subject(); | ||
|
||
constructor( | ||
private cdr: ChangeDetectorRef, | ||
private errorsDirective: ErrorsDirective, | ||
private config: ErrorsConfiguration | ||
) { | ||
this.initConfig(); | ||
} | ||
|
||
ngAfterViewInit() { | ||
this.validateDirective(); | ||
this.listenForm(); | ||
} | ||
|
||
listenForm(): void { | ||
const ngSubmit$ = | ||
this.config.showErrorsWhenFormSubmitted && this.errorsDirective.parentForm | ||
? this.errorsDirective.parentForm.ngSubmit | ||
: NEVER; | ||
|
||
this.errorsDirective.control$ | ||
.pipe( | ||
takeUntil(this.destroy), | ||
filter((c): c is AbstractControl => !!c), | ||
tap((control) => this.calcShouldDisplay(control)), | ||
switchMap((control) => | ||
merge(control.valueChanges, ngSubmit$).pipe( | ||
takeUntil(this.destroy), | ||
map(() => control) | ||
) | ||
), | ||
tap((control) => this.calcShouldDisplay(control)) | ||
) | ||
.subscribe(); | ||
} | ||
|
||
ngOnDestroy() { | ||
this.destroy.next(); | ||
this.destroy.complete(); | ||
} | ||
|
||
private calcShouldDisplay(control: AbstractControl) { | ||
const hasError = control.hasError(this.errorName); | ||
|
||
// could show error if there is one | ||
let couldShowError = false; | ||
|
||
const canShowBasedOnControlDirty = this.canShowBasedOnControlDirty(control); | ||
|
||
const form = this.errorsDirective.parentForm; | ||
if (this.config.showErrorsWhenFormSubmitted) { | ||
couldShowError = form ? form.submitted : canShowBasedOnControlDirty; | ||
} else { | ||
couldShowError = canShowBasedOnControlDirty; | ||
} | ||
|
||
this.changeErrorVisibility( | ||
couldShowError && hasError && control.getError(this.errorName) | ||
); | ||
this.cdr.detectChanges(); | ||
} | ||
|
||
changeErrorVisibility(error: any): void { | ||
this.hidden = !error; | ||
} | ||
|
||
private initConfig() { | ||
if (!this.config) { | ||
this.config = defaultConfig; | ||
return; | ||
} | ||
if (this.config.showErrorsOnlyIfInputDirty == null) { | ||
this.config.showErrorsOnlyIfInputDirty = | ||
defaultConfig.showErrorsOnlyIfInputDirty; | ||
} | ||
if (this.config.showErrorsWhenFormSubmitted == null) { | ||
this.config.showErrorsWhenFormSubmitted = | ||
defaultConfig.showErrorsWhenFormSubmitted; | ||
} | ||
} | ||
|
||
private validateDirective() { | ||
if (this.errorsDirective == null) { | ||
throw new NoParentNgxErrorsError(); | ||
} | ||
|
||
if (typeof this.errorName !== 'string' || this.errorName.trim() === '') { | ||
throw new ValueMustBeStringError(); | ||
} | ||
} | ||
|
||
private canShowBasedOnControlDirty(control: AbstractControl) { | ||
return !this.config.showErrorsOnlyIfInputDirty || control.dirty; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
import { | ||
ChangeDetectorRef, | ||
Directive, | ||
EmbeddedViewRef, | ||
Input, | ||
Optional, | ||
TemplateRef, | ||
ViewContainerRef, | ||
} from '@angular/core'; | ||
import { ErrorBase } from './error.base'; | ||
import { ErrorsDirective } from './errors.directive'; | ||
import { ErrorsConfiguration } from './errors-configuration'; | ||
|
||
export class ObservablesContext { | ||
[key: string]: any; | ||
} | ||
|
||
/** | ||
* Structural directive to provide a rich validation error message for a specific error name. | ||
* Used as a child of ngxErrors directive. | ||
* | ||
* Example: | ||
* ```html | ||
* <div *ngxRichError="'minlength'; let actualLength=actualLength; let requiredLength=requiredLength"> | ||
* Value should be at least {{requiredLength}} long; Right now it's {{actualLength}} | ||
* </div> | ||
* ``` | ||
*/ | ||
@Directive({ | ||
selector: '[ngxRichError]', | ||
}) | ||
export class RichErrorDirective extends ErrorBase { | ||
private ref: EmbeddedViewRef<ObservablesContext> | undefined; | ||
private _context = new ObservablesContext(); | ||
|
||
@Input() set ngxRichError(errorName: string) { | ||
this.errorName = errorName; | ||
} | ||
|
||
constructor( | ||
private template: TemplateRef<ObservablesContext>, | ||
private viewContainer: ViewContainerRef, | ||
cdr: ChangeDetectorRef, | ||
// ErrorsDirective is actually required. | ||
// use @Optional so that we can throw a custom error | ||
@Optional() errorsDirective: ErrorsDirective, | ||
@Optional() config: ErrorsConfiguration | ||
) { | ||
super(cdr, errorsDirective, config); | ||
} | ||
|
||
changeErrorVisibility(error: any): void { | ||
if (error) { | ||
Object.assign(this._context, error); | ||
if (!this.ref) { | ||
this.ref = this.viewContainer.createEmbeddedView( | ||
this.template, | ||
this._context | ||
); | ||
} | ||
} else { | ||
this.viewContainer.clear(); | ||
this.ref = undefined; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
{ $implicit: this._context }
to enable syntax I mentioned in the general comments